Skip to content

jsonapi

This module should reproduce JSON API v1.0 https://jsonapi.org/format/1.0/

JsonLinkType = Union[AnyUrl, Link] module-attribute

Attributes

Bases: BaseModel

Members of the attributes object ("attributes") represent information about the resource object in which it's defined. The keys for Attributes MUST NOT be: relationships links id type

Source code in optimade/models/jsonapi.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
class Attributes(BaseModel):
    """
    Members of the attributes object ("attributes\") represent information about the resource object in which it's defined.
    The keys for Attributes MUST NOT be:
        relationships
        links
        id
        type
    """

    model_config = ConfigDict(extra="allow")

    @model_validator(mode="after")
    def check_illegal_attributes_fields(self) -> "Attributes":
        illegal_fields = ("relationships", "links", "id", "type")
        for field in illegal_fields:
            if hasattr(self, field):
                raise ValueError(
                    f"{illegal_fields} MUST NOT be fields under Attributes"
                )
        return self

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

check_illegal_attributes_fields()

Source code in optimade/models/jsonapi.py
330
331
332
333
334
335
336
337
338
@model_validator(mode="after")
def check_illegal_attributes_fields(self) -> "Attributes":
    illegal_fields = ("relationships", "links", "id", "type")
    for field in illegal_fields:
        if hasattr(self, field):
            raise ValueError(
                f"{illegal_fields} MUST NOT be fields under Attributes"
            )
    return self

BaseResource

Bases: BaseModel

Minimum requirements to represent a Resource

Source code in optimade/models/jsonapi.py
218
219
220
221
222
223
224
class BaseResource(BaseModel):
    """Minimum requirements to represent a Resource"""

    model_config = ConfigDict(json_schema_extra=resource_json_schema_extra)

    id: Annotated[str, StrictField(description="Resource ID")]
    type: Annotated[str, StrictField(description="Resource type")]

id: Annotated[str, StrictField(description='Resource ID')] instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

type: Annotated[str, StrictField(description='Resource type')] instance-attribute

Error

Bases: BaseModel

An error response

Source code in optimade/models/jsonapi.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class Error(BaseModel):
    """An error response"""

    id: Annotated[
        str | None,
        StrictField(
            description="A unique identifier for this particular occurrence of the problem.",
        ),
    ] = None
    links: Annotated[
        ErrorLinks | None, StrictField(description="A links object storing about")
    ] = None
    status: Annotated[
        Annotated[str, BeforeValidator(str)] | None,
        StrictField(
            description="the HTTP status code applicable to this problem, expressed as a string value.",
        ),
    ] = None
    code: Annotated[
        str | None,
        StrictField(
            description="an application-specific error code, expressed as a string value.",
        ),
    ] = None
    title: Annotated[
        str | None,
        StrictField(
            description="A short, human-readable summary of the problem. "
            "It **SHOULD NOT** change from occurrence to occurrence of the problem, except for purposes of localization.",
        ),
    ] = None
    detail: Annotated[
        str | None,
        StrictField(
            description="A human-readable explanation specific to this occurrence of the problem.",
        ),
    ] = None
    source: Annotated[
        ErrorSource | None,
        StrictField(
            description="An object containing references to the source of the error"
        ),
    ] = None
    meta: Annotated[
        Meta | None,
        StrictField(
            description="a meta object containing non-standard meta-information about the error.",
        ),
    ] = None

    def __hash__(self):
        return hash(self.model_dump_json())

code: Annotated[str | None, StrictField(description='an application-specific error code, expressed as a string value.')] = None class-attribute instance-attribute

detail: Annotated[str | None, StrictField(description='A human-readable explanation specific to this occurrence of the problem.')] = None class-attribute instance-attribute

id: Annotated[str | None, StrictField(description='A unique identifier for this particular occurrence of the problem.')] = None class-attribute instance-attribute

meta: Annotated[Meta | None, StrictField(description='a meta object containing non-standard meta-information about the error.')] = None class-attribute instance-attribute

source: Annotated[ErrorSource | None, StrictField(description='An object containing references to the source of the error')] = None class-attribute instance-attribute

status: Annotated[Annotated[str, BeforeValidator(str)] | None, StrictField(description='the HTTP status code applicable to this problem, expressed as a string value.')] = None class-attribute instance-attribute

title: Annotated[str | None, StrictField(description='A short, human-readable summary of the problem. It **SHOULD NOT** change from occurrence to occurrence of the problem, except for purposes of localization.')] = None class-attribute instance-attribute

__hash__()

Source code in optimade/models/jsonapi.py
191
192
def __hash__(self):
    return hash(self.model_dump_json())

Bases: BaseModel

A Links object specific to Error objects

Source code in optimade/models/jsonapi.py
112
113
114
115
116
117
118
119
120
class ErrorLinks(BaseModel):
    """A Links object specific to Error objects"""

    about: Annotated[
        JsonLinkType | None,
        StrictField(
            description="A link that leads to further details about this particular occurrence of the problem.",
        ),
    ] = None

about: Annotated[JsonLinkType | None, StrictField(description='A link that leads to further details about this particular occurrence of the problem.')] = None class-attribute instance-attribute

ErrorSource

Bases: BaseModel

an object containing references to the source of the error

Source code in optimade/models/jsonapi.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class ErrorSource(BaseModel):
    """an object containing references to the source of the error"""

    pointer: Annotated[
        str | None,
        StrictField(
            description="a JSON Pointer [RFC6901] to the associated entity in the request document "
            '[e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].',
        ),
    ] = None
    parameter: Annotated[
        str | None,
        StrictField(
            description="a string indicating which URI query parameter caused the error.",
        ),
    ] = None

parameter: Annotated[str | None, StrictField(description='a string indicating which URI query parameter caused the error.')] = None class-attribute instance-attribute

pointer: Annotated[str | None, StrictField(description='a JSON Pointer [RFC6901] to the associated entity in the request document [e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].')] = None class-attribute instance-attribute

JsonApi

Bases: BaseModel

An object describing the server's implementation

Source code in optimade/models/jsonapi.py
58
59
60
61
62
63
64
65
66
class JsonApi(BaseModel):
    """An object describing the server's implementation"""

    version: Annotated[str, StrictField(description="Version of the json API used")] = (
        "1.0"
    )
    meta: Annotated[
        Meta | None, StrictField(description="Non-standard meta information")
    ] = None

meta: Annotated[Meta | None, StrictField(description='Non-standard meta information')] = None class-attribute instance-attribute

version: Annotated[str, StrictField(description='Version of the json API used')] = '1.0' class-attribute instance-attribute

Bases: BaseModel

A link MUST be represented as either: a string containing the link's URL or a link object.

Source code in optimade/models/jsonapi.py
41
42
43
44
45
46
47
48
49
50
51
52
class Link(BaseModel):
    """A link **MUST** be represented as either: a string containing the link's URL or a link object."""

    href: Annotated[
        AnyUrl, StrictField(description="a string containing the link's URL.")
    ]
    meta: Annotated[
        Meta | None,
        StrictField(
            description="a meta object containing non-standard meta-information about the link.",
        ),
    ] = None

href: Annotated[AnyUrl, StrictField(description="a string containing the link's URL.")] instance-attribute

meta: Annotated[Meta | None, StrictField(description='a meta object containing non-standard meta-information about the link.')] = None class-attribute instance-attribute

Meta

Bases: BaseModel

Non-standard meta-information that can not be represented as an attribute or relationship.

Source code in optimade/models/jsonapi.py
35
36
37
38
class Meta(BaseModel):
    """Non-standard meta-information that can not be represented as an attribute or relationship."""

    model_config = ConfigDict(extra="allow")

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

Relationship

Bases: BaseModel

Representation references from the resource object in which it's defined to other resource objects.

Source code in optimade/models/jsonapi.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class Relationship(BaseModel):
    """Representation references from the resource object in which it's defined to other resource objects."""

    links: Annotated[
        RelationshipLinks | None,
        StrictField(
            description="a links object containing at least one of the following: self, related",
        ),
    ] = None
    data: Annotated[
        BaseResource | list[BaseResource] | None,
        StrictField(description="Resource linkage"),
    ] = None
    meta: Annotated[
        Meta | None,
        StrictField(
            description="a meta object that contains non-standard meta-information about the relationship.",
        ),
    ] = None

    @model_validator(mode="after")
    def at_least_one_relationship_key_must_be_set(self) -> "Relationship":
        if self.links is None and self.data is None and self.meta is None:
            raise ValueError(
                "Either 'links', 'data', or 'meta' MUST be specified for Relationship"
            )
        return self

data: Annotated[BaseResource | list[BaseResource] | None, StrictField(description='Resource linkage')] = None class-attribute instance-attribute

meta: Annotated[Meta | None, StrictField(description='a meta object that contains non-standard meta-information about the relationship.')] = None class-attribute instance-attribute

at_least_one_relationship_key_must_be_set()

Source code in optimade/models/jsonapi.py
279
280
281
282
283
284
285
@model_validator(mode="after")
def at_least_one_relationship_key_must_be_set(self) -> "Relationship":
    if self.links is None and self.data is None and self.meta is None:
        raise ValueError(
            "Either 'links', 'data', or 'meta' MUST be specified for Relationship"
        )
    return self

Bases: BaseModel

A resource object MAY contain references to other resource objects ("relationships"). Relationships may be to-one or to-many. Relationships can be specified by including a member in a resource's links object.

Source code in optimade/models/jsonapi.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
class RelationshipLinks(BaseModel):
    """A resource object **MAY** contain references to other resource objects ("relationships").
    Relationships may be to-one or to-many.
    Relationships can be specified by including a member in a resource's links object.

    """

    self: Annotated[
        JsonLinkType | None,
        StrictField(
            description="""A link for the relationship itself (a 'relationship link').
This link allows the client to directly manipulate the relationship.
When fetched successfully, this link returns the [linkage](https://jsonapi.org/format/1.0/#document-resource-object-linkage) for the related resources as its primary data.
(See [Fetching Relationships](https://jsonapi.org/format/1.0/#fetching-relationships).)""",
        ),
    ] = None
    related: Annotated[
        JsonLinkType | None,
        StrictField(
            description="A [related resource link](https://jsonapi.org/format/1.0/#document-resource-object-related-resource-links).",
        ),
    ] = None

    @model_validator(mode="after")
    def either_self_or_related_must_be_specified(self) -> "RelationshipLinks":
        if self.self is None and self.related is None:
            raise ValueError(
                "Either 'self' or 'related' MUST be specified for RelationshipLinks"
            )
        return self

related: Annotated[JsonLinkType | None, StrictField(description='A [related resource link](https://jsonapi.org/format/1.0/#document-resource-object-related-resource-links).')] = None class-attribute instance-attribute

self: Annotated[JsonLinkType | None, StrictField(description="A link for the relationship itself (a 'relationship link').\nThis link allows the client to directly manipulate the relationship.\nWhen fetched successfully, this link returns the [linkage](https://jsonapi.org/format/1.0/#document-resource-object-linkage) for the related resources as its primary data.\n(See [Fetching Relationships](https://jsonapi.org/format/1.0/#fetching-relationships).)")] = None class-attribute instance-attribute

Source code in optimade/models/jsonapi.py
250
251
252
253
254
255
256
@model_validator(mode="after")
def either_self_or_related_must_be_specified(self) -> "RelationshipLinks":
    if self.self is None and self.related is None:
        raise ValueError(
            "Either 'self' or 'related' MUST be specified for RelationshipLinks"
        )
    return self

Relationships

Bases: BaseModel

Members of the relationships object ("relationships") represent references from the resource object in which it's defined to other resource objects. Keys MUST NOT be: type id

Source code in optimade/models/jsonapi.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
class Relationships(BaseModel):
    """
    Members of the relationships object (\"relationships\") represent references from the resource object in which it's defined to other resource objects.
    Keys MUST NOT be:
        type
        id
    """

    @model_validator(mode="after")
    def check_illegal_relationships_fields(self) -> "Relationships":
        illegal_fields = ("id", "type")
        for field in illegal_fields:
            if hasattr(self, field):
                raise ValueError(
                    f"{illegal_fields} MUST NOT be fields under Relationships"
                )
        return self

check_illegal_relationships_fields()

Source code in optimade/models/jsonapi.py
296
297
298
299
300
301
302
303
304
@model_validator(mode="after")
def check_illegal_relationships_fields(self) -> "Relationships":
    illegal_fields = ("id", "type")
    for field in illegal_fields:
        if hasattr(self, field):
            raise ValueError(
                f"{illegal_fields} MUST NOT be fields under Relationships"
            )
    return self

Resource

Bases: BaseResource

Resource objects appear in a JSON API document to represent resources.

Source code in optimade/models/jsonapi.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
class Resource(BaseResource):
    """Resource objects appear in a JSON API document to represent resources."""

    links: Annotated[
        ResourceLinks | None,
        StrictField(
            description="a links object containing links related to the resource."
        ),
    ] = None
    meta: Annotated[
        Meta | None,
        StrictField(
            description="a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.",
        ),
    ] = None
    attributes: Annotated[
        Attributes | None,
        StrictField(
            description="an attributes object representing some of the resource’s data.",
        ),
    ] = None
    relationships: Annotated[
        Relationships | None,
        StrictField(
            description="""[Relationships object](https://jsonapi.org/format/1.0/#document-resource-object-relationships)
describing relationships between the resource and other JSON API resources.""",
        ),
    ] = None

attributes: Annotated[Attributes | None, StrictField(description='an attributes object representing some of the resource’s data.')] = None class-attribute instance-attribute

id: Annotated[str, StrictField(description='Resource ID')] instance-attribute

meta: Annotated[Meta | None, StrictField(description='a meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.')] = None class-attribute instance-attribute

model_config = ConfigDict(json_schema_extra=resource_json_schema_extra) class-attribute instance-attribute

relationships: Annotated[Relationships | None, StrictField(description='[Relationships object](https://jsonapi.org/format/1.0/#document-resource-object-relationships)\ndescribing relationships between the resource and other JSON API resources.')] = None class-attribute instance-attribute

type: Annotated[str, StrictField(description='Resource type')] instance-attribute

Bases: BaseModel

A Resource Links object

Source code in optimade/models/jsonapi.py
307
308
309
310
311
312
313
314
315
class ResourceLinks(BaseModel):
    """A Resource Links object"""

    self: Annotated[
        JsonLinkType | None,
        StrictField(
            description="A link that identifies the resource represented by the resource object.",
        ),
    ] = None

self: Annotated[JsonLinkType | None, StrictField(description='A link that identifies the resource represented by the resource object.')] = None class-attribute instance-attribute

Response

Bases: BaseModel

A top-level response.

Source code in optimade/models/jsonapi.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class Response(BaseModel):
    """A top-level response."""

    data: Annotated[
        None | Resource | list[Resource] | None,
        StrictField(description="Outputted Data", uniqueItems=True),
    ] = None
    meta: Annotated[
        Meta | None,
        StrictField(
            description="A meta object containing non-standard information related to the Success",
        ),
    ] = None
    errors: Annotated[
        list[Error] | None,
        StrictField(description="A list of unique errors", uniqueItems=True),
    ] = None
    included: Annotated[
        list[Resource] | None,
        StrictField(
            description="A list of unique included resources", uniqueItems=True
        ),
    ] = None
    links: Annotated[
        ToplevelLinks | None,
        StrictField(description="Links associated with the primary data or errors"),
    ] = None
    jsonapi: Annotated[
        JsonApi | None,
        StrictField(description="Information about the JSON API used"),
    ] = None

    @model_validator(mode="after")
    def either_data_meta_or_errors_must_be_set(self) -> "Response":
        required_fields = ("data", "meta", "errors")
        if not any(field in self.model_fields_set for field in required_fields):
            raise ValueError(
                f"At least one of {required_fields} MUST be specified in the top-level response"
            )
        if "errors" in self.model_fields_set and not self.errors:
            raise ValueError("Errors MUST NOT be an empty or 'null' value.")
        return self

    model_config = ConfigDict(
        json_encoders={
            datetime: lambda v: v.astimezone(timezone.utc).strftime(
                "%Y-%m-%dT%H:%M:%SZ"
            )
        }
    )
    """The specification mandates that datetimes must be encoded following
    [RFC3339](https://tools.ietf.org/html/rfc3339), which does not support
    fractional seconds, thus they must be stripped in the response. This can
    cause issues when the underlying database contains fields that do include
    microseconds, as filters may return unexpected results.
    """

data: Annotated[None | Resource | list[Resource] | None, StrictField(description='Outputted Data', uniqueItems=True)] = None class-attribute instance-attribute

errors: Annotated[list[Error] | None, StrictField(description='A list of unique errors', uniqueItems=True)] = None class-attribute instance-attribute

included: Annotated[list[Resource] | None, StrictField(description='A list of unique included resources', uniqueItems=True)] = None class-attribute instance-attribute

jsonapi: Annotated[JsonApi | None, StrictField(description='Information about the JSON API used')] = None class-attribute instance-attribute

meta: Annotated[Meta | None, StrictField(description='A meta object containing non-standard information related to the Success')] = None class-attribute instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda v: v.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')}) class-attribute instance-attribute

The specification mandates that datetimes must be encoded following RFC3339, which does not support fractional seconds, thus they must be stripped in the response. This can cause issues when the underlying database contains fields that do include microseconds, as filters may return unexpected results.

either_data_meta_or_errors_must_be_set()

Source code in optimade/models/jsonapi.py
403
404
405
406
407
408
409
410
411
412
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Response":
    required_fields = ("data", "meta", "errors")
    if not any(field in self.model_fields_set for field in required_fields):
        raise ValueError(
            f"At least one of {required_fields} MUST be specified in the top-level response"
        )
    if "errors" in self.model_fields_set and not self.errors:
        raise ValueError("Errors MUST NOT be an empty or 'null' value.")
    return self

Bases: BaseModel

A set of Links objects, possibly including pagination

Source code in optimade/models/jsonapi.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class ToplevelLinks(BaseModel):
    """A set of Links objects, possibly including pagination"""

    model_config = ConfigDict(extra="allow")

    self: Annotated[
        JsonLinkType | None, StrictField(description="A link to itself")
    ] = None
    related: Annotated[
        JsonLinkType | None, StrictField(description="A related resource link")
    ] = None

    # Pagination
    first: Annotated[
        JsonLinkType | None, StrictField(description="The first page of data")
    ] = None
    last: Annotated[
        JsonLinkType | None, StrictField(description="The last page of data")
    ] = None
    prev: Annotated[
        JsonLinkType | None, StrictField(description="The previous page of data")
    ] = None
    next: Annotated[
        JsonLinkType | None, StrictField(description="The next page of data")
    ] = None

    @model_validator(mode="after")
    def check_additional_keys_are_links(self) -> "ToplevelLinks":
        """The `ToplevelLinks` class allows any additional keys, as long as
        they are also Links or Urls themselves.

        """
        for field, value in self:
            if field not in self.model_fields:
                setattr(
                    self,
                    field,
                    TypeAdapter(Optional[JsonLinkType]).validate_python(value),
                )

        return self

first: Annotated[JsonLinkType | None, StrictField(description='The first page of data')] = None class-attribute instance-attribute

last: Annotated[JsonLinkType | None, StrictField(description='The last page of data')] = None class-attribute instance-attribute

model_config = ConfigDict(extra='allow') class-attribute instance-attribute

next: Annotated[JsonLinkType | None, StrictField(description='The next page of data')] = None class-attribute instance-attribute

prev: Annotated[JsonLinkType | None, StrictField(description='The previous page of data')] = None class-attribute instance-attribute

related: Annotated[JsonLinkType | None, StrictField(description='A related resource link')] = None class-attribute instance-attribute

self: Annotated[JsonLinkType | None, StrictField(description='A link to itself')] = None class-attribute instance-attribute

The ToplevelLinks class allows any additional keys, as long as they are also Links or Urls themselves.

Source code in optimade/models/jsonapi.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@model_validator(mode="after")
def check_additional_keys_are_links(self) -> "ToplevelLinks":
    """The `ToplevelLinks` class allows any additional keys, as long as
    they are also Links or Urls themselves.

    """
    for field, value in self:
        if field not in self.model_fields:
            setattr(
                self,
                field,
                TypeAdapter(Optional[JsonLinkType]).validate_python(value),
            )

    return self

resource_json_schema_extra(schema, model)

Ensure id and type are the first two entries in the list required properties.

Note

This requires that id and type are the first model fields defined for all sub-models of BaseResource.

Source code in optimade/models/jsonapi.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
def resource_json_schema_extra(
    schema: dict[str, Any], model: type["BaseResource"]
) -> None:
    """Ensure `id` and `type` are the first two entries in the list required properties.

    Note:
        This _requires_ that `id` and `type` are the _first_ model fields defined
        for all sub-models of `BaseResource`.

    """
    if "id" not in schema.get("required", []):
        schema["required"] = ["id"] + schema.get("required", [])
    if "type" not in schema.get("required", []):
        required = []
        for field in schema.get("required", []):
            required.append(field)
            if field == "id":
                # To make sure the property order match the listed properties,
                # this ensures "type" is added immediately after "id".
                required.append("type")
        schema["required"] = required