Skip to content

responses

__all__ = ('ErrorResponse', 'EntryInfoResponse', 'IndexInfoResponse', 'InfoResponse', 'LinksResponse', 'EntryResponseOne', 'EntryResponseMany', 'StructureResponseOne', 'StructureResponseMany', 'ReferenceResponseOne', 'ReferenceResponseMany') module-attribute

BaseInfoResource

Bases: Resource

Source code in optimade/models/baseinfo.py
126
127
128
129
class BaseInfoResource(Resource):
    id: Literal["/"] = "/"
    type: Literal["info"] = "info"
    attributes: BaseInfoAttributes

attributes: BaseInfoAttributes instance-attribute

id: Literal['/'] = '/' class-attribute instance-attribute

meta: Annotated[Optional[Meta], 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[Optional[Relationships], 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: Literal['info'] = 'info' class-attribute instance-attribute

EntryInfoResource

Bases: BaseModel

Source code in optimade/models/entries.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class EntryInfoResource(BaseModel):
    formats: Annotated[
        list[str],
        StrictField(
            description="List of output formats available for this type of entry."
        ),
    ]

    description: Annotated[str, StrictField(description="Description of the entry.")]

    properties: Annotated[
        dict[str, EntryInfoProperty],
        StrictField(
            description="A dictionary describing queryable properties for this entry type, where each key is a property name.",
        ),
    ]

    output_fields_by_format: Annotated[
        dict[str, list[str]],
        StrictField(
            description="Dictionary of available output fields for this entry type, where the keys are the values of the `formats` list and the values are the keys of the `properties` dictionary.",
        ),
    ]

description: Annotated[str, StrictField(description='Description of the entry.')] instance-attribute

formats: Annotated[list[str], StrictField(description='List of output formats available for this type of entry.')] instance-attribute

output_fields_by_format: Annotated[dict[str, list[str]], StrictField(description='Dictionary of available output fields for this entry type, where the keys are the values of the `formats` list and the values are the keys of the `properties` dictionary.')] instance-attribute

properties: Annotated[dict[str, EntryInfoProperty], StrictField(description='A dictionary describing queryable properties for this entry type, where each key is a property name.')] instance-attribute

EntryInfoResponse

Bases: Success

Source code in optimade/models/responses.py
59
60
61
62
63
class EntryInfoResponse(Success):
    data: Annotated[
        EntryInfoResource,
        StrictField(description="OPTIMADE information for an entry endpoint."),
    ]

data: Annotated[EntryInfoResource, StrictField(description='OPTIMADE information for an entry endpoint.')] instance-attribute

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

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

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

EntryResource

Bases: Resource

The base model for an entry resource.

Source code in optimade/models/entries.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
class EntryResource(Resource):
    """The base model for an entry resource."""

    id: Annotated[
        str,
        OptimadeField(
            description="""An entry's ID as defined in section Definition of Terms.

- **Type**: string.

- **Requirements/Conventions**:
    - **Support**: MUST be supported by all implementations, MUST NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - **Response**: REQUIRED in the response.

- **Examples**:
    - `"db/1234567"`
    - `"cod/2000000"`
    - `"cod/2000000@1234567"`
    - `"nomad/L1234567890"`
    - `"42"`""",
            support=SupportLevel.MUST,
            queryable=SupportLevel.MUST,
        ),
    ]

    type: Annotated[
        str,
        OptimadeField(
            description="""The name of the type of an entry.

- **Type**: string.

- **Requirements/Conventions**:
    - **Support**: MUST be supported by all implementations, MUST NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - **Response**: REQUIRED in the response.
    - MUST be an existing entry type.
    - The entry of type `<type>` and ID `<id>` MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.

- **Example**: `"structures"`""",
            support=SupportLevel.MUST,
            queryable=SupportLevel.MUST,
        ),
    ]

    attributes: Annotated[
        EntryResourceAttributes,
        StrictField(
            description="""A dictionary, containing key-value pairs representing the entry's properties, except for `type` and `id`.
Database-provider-specific properties need to include the database-provider-specific prefix (see section on Database-Provider-Specific Namespace Prefixes).""",
        ),
    ]

    relationships: Annotated[
        Optional[EntryRelationships],
        StrictField(
            description="""A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships).
The OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.""",
        ),
    ] = None

attributes: Annotated[EntryResourceAttributes, StrictField(description="A dictionary, containing key-value pairs representing the entry's properties, except for `type` and `id`.\nDatabase-provider-specific properties need to include the database-provider-specific prefix (see section on Database-Provider-Specific Namespace Prefixes).")] instance-attribute

id: Annotated[str, OptimadeField(description='An entry\'s ID as defined in section Definition of Terms.\n\n- **Type**: string.\n\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n\n- **Examples**:\n - `"db/1234567"`\n - `"cod/2000000"`\n - `"cod/2000000@1234567"`\n - `"nomad/L1234567890"`\n - `"42"`', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] instance-attribute

meta: Annotated[Optional[Meta], 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[Optional[EntryRelationships], StrictField(description='A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships).\nThe OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.')] = None class-attribute instance-attribute

type: Annotated[str, OptimadeField(description='The name of the type of an entry.\n\n- **Type**: string.\n\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n - MUST be an existing entry type.\n - The entry of type `<type>` and ID `<id>` MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.\n\n- **Example**: `"structures"`', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] instance-attribute

EntryResponseMany

Bases: Success

Source code in optimade/models/responses.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class EntryResponseMany(Success):
    data: Annotated[  # type: ignore[assignment]
        Union[list[EntryResource], list[dict[str, Any]]],
        StrictField(
            description="List of unique OPTIMADE entry resource objects.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ]
    included: Annotated[
        Optional[Union[list[EntryResource], list[dict[str, Any]]]],
        StrictField(
            description="A list of unique included OPTIMADE entry resources.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ] = None  # type: ignore[assignment]

data: Annotated[Union[list[EntryResource], list[dict[str, Any]]], StrictField(description='List of unique OPTIMADE entry resource objects.', uniqueItems=True, union_mode=left_to_right)] instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

EntryResponseOne

Bases: Success

Source code in optimade/models/responses.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class EntryResponseOne(Success):
    data: Annotated[
        Optional[Union[EntryResource, dict[str, Any]]],
        StrictField(
            description="The single entry resource returned by this query.",
            union_mode="left_to_right",
        ),
    ] = None  # type: ignore[assignment]
    included: Annotated[
        Optional[Union[list[EntryResource], list[dict[str, Any]]]],
        StrictField(
            description="A list of unique included OPTIMADE entry resources.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ] = None  # type: ignore[assignment]

data: Annotated[Optional[Union[EntryResource, dict[str, Any]]], StrictField(description='The single entry resource returned by this query.', union_mode=left_to_right)] = None class-attribute instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

ErrorResponse

Bases: Response

errors MUST be present and data MUST be skipped

Source code in optimade/models/responses.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class ErrorResponse(Response):
    """errors MUST be present and data MUST be skipped"""

    meta: Annotated[
        ResponseMeta,
        StrictField(description="A meta object containing non-standard information."),
    ]
    errors: Annotated[
        list[OptimadeError],
        StrictField(
            description="A list of OPTIMADE-specific JSON API error objects, where the field detail MUST be present.",
            uniqueItems=True,
        ),
    ]

    @model_validator(mode="after")
    def data_must_be_skipped(self) -> "ErrorResponse":
        if self.data or "data" in self.model_fields_set:
            raise ValueError("data MUST be skipped for failures reporting errors.")
        return self

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

errors: Annotated[list[OptimadeError], StrictField(description='A list of OPTIMADE-specific JSON API error objects, where the field detail MUST be present.', uniqueItems=True)] instance-attribute

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

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information.')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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.

data_must_be_skipped()

Source code in optimade/models/responses.py
46
47
48
49
50
@model_validator(mode="after")
def data_must_be_skipped(self) -> "ErrorResponse":
    if self.data or "data" in self.model_fields_set:
        raise ValueError("data MUST be skipped for failures reporting errors.")
    return self

either_data_meta_or_errors_must_be_set()

Source code in optimade/models/jsonapi.py
402
403
404
405
406
407
408
409
410
411
@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

IndexInfoResource

Bases: BaseInfoResource

Index Meta-Database Base URL Info endpoint resource

Source code in optimade/models/index_metadb.py
46
47
48
49
50
51
52
53
54
55
56
57
class IndexInfoResource(BaseInfoResource):
    """Index Meta-Database Base URL Info endpoint resource"""

    attributes: IndexInfoAttributes
    relationships: Annotated[  # type: ignore[assignment]
        Optional[dict[Literal["default"], IndexRelationship]],
        StrictField(
            title="Relationships",
            description="""Reference to the Links identifier object under the `links` endpoint that the provider has chosen as their 'default' OPTIMADE API database.
A client SHOULD present this database as the first choice when an end-user chooses this provider.""",
        ),
    ]

attributes: IndexInfoAttributes instance-attribute

id: Literal['/'] = '/' class-attribute instance-attribute

meta: Annotated[Optional[Meta], 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[Optional[dict[Literal['default'], IndexRelationship]], StrictField(title=Relationships, description="Reference to the Links identifier object under the `links` endpoint that the provider has chosen as their 'default' OPTIMADE API database.\nA client SHOULD present this database as the first choice when an end-user chooses this provider.")] instance-attribute

type: Literal['info'] = 'info' class-attribute instance-attribute

IndexInfoResponse

Bases: Success

Source code in optimade/models/responses.py
53
54
55
56
class IndexInfoResponse(Success):
    data: Annotated[
        IndexInfoResource, StrictField(description="Index meta-database /info data.")
    ]

data: Annotated[IndexInfoResource, StrictField(description='Index meta-database /info data.')] instance-attribute

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

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

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

InfoResponse

Bases: Success

Source code in optimade/models/responses.py
66
67
68
69
class InfoResponse(Success):
    data: Annotated[
        BaseInfoResource, StrictField(description="The implementations /info data.")
    ]

data: Annotated[BaseInfoResource, StrictField(description='The implementations /info data.')] instance-attribute

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

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

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

LinksResource

Bases: EntryResource

A Links endpoint resource object

Source code in optimade/models/links.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class LinksResource(EntryResource):
    """A Links endpoint resource object"""

    type: Annotated[
        Literal["links"],
        StrictField(
            description="These objects are described in detail in the section Links Endpoint",
            pattern="^links$",
        ),
    ] = "links"

    attributes: Annotated[
        LinksResourceAttributes,
        StrictField(
            description="A dictionary containing key-value pairs representing the Links resource's properties.",
        ),
    ]

    @model_validator(mode="after")
    def relationships_must_not_be_present(self) -> "LinksResource":
        if self.relationships or "relationships" in self.model_fields_set:
            raise ValueError('"relationships" is not allowed for links resources')
        return self

attributes: Annotated[LinksResourceAttributes, StrictField(description="A dictionary containing key-value pairs representing the Links resource's properties.")] instance-attribute

id: Annotated[str, OptimadeField(description='An entry\'s ID as defined in section Definition of Terms.\n\n- **Type**: string.\n\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n\n- **Examples**:\n - `"db/1234567"`\n - `"cod/2000000"`\n - `"cod/2000000@1234567"`\n - `"nomad/L1234567890"`\n - `"42"`', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] instance-attribute

meta: Annotated[Optional[Meta], 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[Optional[EntryRelationships], StrictField(description='A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships).\nThe OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.')] = None class-attribute instance-attribute

type: Annotated[Literal['links'], StrictField(description='These objects are described in detail in the section Links Endpoint', pattern='^links$')] = 'links' class-attribute instance-attribute

relationships_must_not_be_present()

Source code in optimade/models/links.py
116
117
118
119
120
@model_validator(mode="after")
def relationships_must_not_be_present(self) -> "LinksResource":
    if self.relationships or "relationships" in self.model_fields_set:
        raise ValueError('"relationships" is not allowed for links resources')
    return self

LinksResponse

Bases: EntryResponseMany

Source code in optimade/models/responses.py
109
110
111
112
113
114
115
116
117
class LinksResponse(EntryResponseMany):
    data: Annotated[
        Union[list[LinksResource], list[dict[str, Any]]],
        StrictField(
            description="List of unique OPTIMADE links resource objects.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ]

data: Annotated[Union[list[LinksResource], list[dict[str, Any]]], StrictField(description='List of unique OPTIMADE links resource objects.', uniqueItems=True, union_mode=left_to_right)] instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

OptimadeError

Bases: Error

detail MUST be present

Source code in optimade/models/optimade_json.py
126
127
128
129
130
131
132
133
134
class OptimadeError(jsonapi.Error):
    """detail MUST be present"""

    detail: Annotated[
        str,
        StrictField(
            description="A human-readable explanation specific to this occurrence of the problem.",
        ),
    ]

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

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

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

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

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

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

title: Annotated[Optional[str], 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
190
191
def __hash__(self):
    return hash(self.model_dump_json())

ReferenceResource

Bases: EntryResource

The references entries describe bibliographic references.

The following properties are used to provide the bibliographic details:

  • address, annote, booktitle, chapter, crossref, edition, howpublished, institution, journal, key, month, note, number, organization, pages, publisher, school, series, title, volume, year: meanings of these properties match the BibTeX specification, values are strings;
  • bib_type: type of the reference, corresponding to type property in the BibTeX specification, value is string;
  • authors and editors: lists of person objects which are dictionaries with the following keys:
    • name: Full name of the person, REQUIRED.
    • firstname, lastname: Parts of the person's name, OPTIONAL.
  • doi and url: values are strings.
  • Requirements/Conventions:
    • Support: OPTIONAL support in implementations, i.e., any of the properties MAY be null.
    • Query: Support for queries on any of these properties is OPTIONAL. If supported, filters MAY support only a subset of comparison operators.
    • Every references entry MUST contain at least one of the properties.
Source code in optimade/models/references.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class ReferenceResource(EntryResource):
    """The `references` entries describe bibliographic references.

    The following properties are used to provide the bibliographic details:

    - **address**, **annote**, **booktitle**, **chapter**, **crossref**, **edition**, **howpublished**, **institution**, **journal**, **key**, **month**, **note**, **number**, **organization**, **pages**, **publisher**, **school**, **series**, **title**, **volume**, **year**: meanings of these properties match the [BibTeX specification](http://bibtexml.sourceforge.net/btxdoc.pdf), values are strings;
    - **bib_type**: type of the reference, corresponding to **type** property in the BibTeX specification, value is string;
    - **authors** and **editors**: lists of *person objects* which are dictionaries with the following keys:
        - **name**: Full name of the person, REQUIRED.
        - **firstname**, **lastname**: Parts of the person's name, OPTIONAL.
    - **doi** and **url**: values are strings.
    - **Requirements/Conventions**:
        - **Support**: OPTIONAL support in implementations, i.e., any of the properties MAY be `null`.
        - **Query**: Support for queries on any of these properties is OPTIONAL.
            If supported, filters MAY support only a subset of comparison operators.
        - Every references entry MUST contain at least one of the properties.

    """

    type: Annotated[
        Literal["references"],
        OptimadeField(
            description="""The name of the type of an entry.
- **Type**: string.
- **Requirements/Conventions**:
    - **Support**: MUST be supported by all implementations, MUST NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - **Response**: REQUIRED in the response.
    - MUST be an existing entry type.
    - The entry of type <type> and ID <id> MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.
- **Example**: `"structures"`""",
            pattern="^references$",
            support=SupportLevel.MUST,
            queryable=SupportLevel.MUST,
        ),
    ] = "references"
    attributes: ReferenceResourceAttributes

    @field_validator("attributes", mode="before")
    @classmethod
    def validate_attributes(cls, value: Any) -> dict[str, Any]:
        if not isinstance(value, dict):
            if isinstance(value, BaseModel):
                value = value.model_dump()
            else:
                raise TypeError("attributes field must be a mapping")
        if not any(prop[1] is not None for prop in value):
            raise ValueError("reference object must have at least one field defined")
        return value

attributes: ReferenceResourceAttributes instance-attribute

id: Annotated[str, OptimadeField(description='An entry\'s ID as defined in section Definition of Terms.\n\n- **Type**: string.\n\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n\n- **Examples**:\n - `"db/1234567"`\n - `"cod/2000000"`\n - `"cod/2000000@1234567"`\n - `"nomad/L1234567890"`\n - `"42"`', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] instance-attribute

meta: Annotated[Optional[Meta], 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[Optional[EntryRelationships], StrictField(description='A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships).\nThe OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.')] = None class-attribute instance-attribute

type: Annotated[Literal['references'], OptimadeField(description='The name of the type of an entry.\n- **Type**: string.\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n - MUST be an existing entry type.\n - The entry of type <type> and ID <id> MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.\n- **Example**: `"structures"`', pattern='^references$', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] = 'references' class-attribute instance-attribute

validate_attributes(value) classmethod

Source code in optimade/models/references.py
323
324
325
326
327
328
329
330
331
332
333
@field_validator("attributes", mode="before")
@classmethod
def validate_attributes(cls, value: Any) -> dict[str, Any]:
    if not isinstance(value, dict):
        if isinstance(value, BaseModel):
            value = value.model_dump()
        else:
            raise TypeError("attributes field must be a mapping")
    if not any(prop[1] is not None for prop in value):
        raise ValueError("reference object must have at least one field defined")
    return value

ReferenceResponseMany

Bases: EntryResponseMany

Source code in optimade/models/responses.py
151
152
153
154
155
156
157
158
159
class ReferenceResponseMany(EntryResponseMany):
    data: Annotated[
        Union[list[ReferenceResource], list[dict[str, Any]]],
        StrictField(
            description="List of unique OPTIMADE references entry resource objects.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ]

data: Annotated[Union[list[ReferenceResource], list[dict[str, Any]]], StrictField(description='List of unique OPTIMADE references entry resource objects.', uniqueItems=True, union_mode=left_to_right)] instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

ReferenceResponseOne

Bases: EntryResponseOne

Source code in optimade/models/responses.py
141
142
143
144
145
146
147
148
class ReferenceResponseOne(EntryResponseOne):
    data: Annotated[
        Optional[Union[ReferenceResource, dict[str, Any]]],
        StrictField(
            description="A single references entry resource.",
            union_mode="left_to_right",
        ),
    ]

data: Annotated[Optional[Union[ReferenceResource, dict[str, Any]]], StrictField(description='A single references entry resource.', union_mode=left_to_right)] instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

Response

Bases: BaseModel

A top-level response.

Source code in optimade/models/jsonapi.py
370
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
class Response(BaseModel):
    """A top-level response."""

    data: Annotated[
        Optional[Union[None, Resource, list[Resource]]],
        StrictField(description="Outputted Data", uniqueItems=True),
    ] = None
    meta: Annotated[
        Optional[Meta],
        StrictField(
            description="A meta object containing non-standard information related to the Success",
        ),
    ] = None
    errors: Annotated[
        Optional[list[Error]],
        StrictField(description="A list of unique errors", uniqueItems=True),
    ] = None
    included: Annotated[
        Optional[list[Resource]],
        StrictField(
            description="A list of unique included resources", uniqueItems=True
        ),
    ] = None
    links: Annotated[
        Optional[ToplevelLinks],
        StrictField(description="Links associated with the primary data or errors"),
    ] = None
    jsonapi: Annotated[
        Optional[JsonApi],
        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[Optional[Union[None, Resource, list[Resource]]], StrictField(description='Outputted Data', uniqueItems=True)] = None class-attribute instance-attribute

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

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

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

meta: Annotated[Optional[Meta], 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.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
402
403
404
405
406
407
408
409
410
411
@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

ResponseMeta

Bases: Meta

A JSON API meta member that contains JSON API meta objects of non-standard meta-information.

OPTIONAL additional information global to the query that is not specified in this document, MUST start with a database-provider-specific prefix.

Source code in optimade/models/optimade_json.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
369
370
371
372
373
374
375
376
class ResponseMeta(jsonapi.Meta):
    """
    A [JSON API meta member](https://jsonapi.org/format/1.0#document-meta)
    that contains JSON API meta objects of non-standard
    meta-information.

    OPTIONAL additional information global to the query that is not
    specified in this document, MUST start with a
    database-provider-specific prefix.
    """

    query: Annotated[
        ResponseMetaQuery,
        StrictField(description="Information on the Query that was requested"),
    ]

    api_version: Annotated[
        SemanticVersion,
        StrictField(
            description="""Presently used full version of the OPTIMADE API.
The version number string MUST NOT be prefixed by, e.g., "v".
Examples: `1.0.0`, `1.0.0-rc.2`.""",
        ),
    ]

    more_data_available: Annotated[
        bool,
        StrictField(
            description="`false` if the response contains all data for the request (e.g., a request issued to a single entry endpoint, or a `filter` query at the last page of a paginated response) and `true` if the response is incomplete in the sense that multiple objects match the request, and not all of them have been included in the response (e.g., a query with multiple pages that is not at the last page).",
        ),
    ]

    # start of "SHOULD" fields for meta response
    optimade_schema: Annotated[
        Optional[jsonapi.JsonLinkType],
        StrictField(
            alias="schema",
            description="""A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) that points to a schema for the response.
If it is a string, or a dictionary containing no `meta` field, the provided URL MUST point at an [OpenAPI](https://swagger.io/specification/) schema.
It is possible that future versions of this specification allows for alternative schema types.
Hence, if the `meta` field of the JSON API links object is provided and contains a field `schema_type` that is not equal to the string `OpenAPI` the client MUST not handle failures to parse the schema or to validate the response against the schema as errors.""",
        ),
    ] = None

    time_stamp: Annotated[
        Optional[datetime],
        StrictField(
            description="A timestamp containing the date and time at which the query was executed.",
        ),
    ] = None

    data_returned: Annotated[
        Optional[int],
        StrictField(
            description="An integer containing the total number of data resource objects returned for the current `filter` query, independent of pagination.",
            ge=0,
        ),
    ] = None

    provider: Annotated[
        Optional[Provider],
        StrictField(
            description="information on the database provider of the implementation."
        ),
    ] = None

    # start of "MAY" fields for meta response
    data_available: Annotated[
        Optional[int],
        StrictField(
            description="An integer containing the total number of data resource objects available in the database for the endpoint.",
        ),
    ] = None

    last_id: Annotated[
        Optional[str],
        StrictField(description="a string containing the last ID returned"),
    ] = None

    response_message: Annotated[
        Optional[str], StrictField(description="response string from the server")
    ] = None

    implementation: Annotated[
        Optional[Implementation],
        StrictField(description="a dictionary describing the server implementation"),
    ] = None

    warnings: Annotated[
        Optional[list[Warnings]],
        StrictField(
            description="""A list of warning resource objects representing non-critical errors or warnings.
A warning resource object is defined similarly to a [JSON API error object](http://jsonapi.org/format/1.0/#error-objects), but MUST also include the field `type`, which MUST have the value `"warning"`.
The field `detail` MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features.
The field `status`, representing a HTTP response status code, MUST NOT be present for a warning resource object.
This is an exclusive field for error resource objects.""",
            uniqueItems=True,
        ),
    ] = None

api_version: Annotated[SemanticVersion, StrictField(description='Presently used full version of the OPTIMADE API.\nThe version number string MUST NOT be prefixed by, e.g., "v".\nExamples: `1.0.0`, `1.0.0-rc.2`.')] instance-attribute

data_available: Annotated[Optional[int], StrictField(description='An integer containing the total number of data resource objects available in the database for the endpoint.')] = None class-attribute instance-attribute

data_returned: Annotated[Optional[int], StrictField(description='An integer containing the total number of data resource objects returned for the current `filter` query, independent of pagination.', ge=0)] = None class-attribute instance-attribute

implementation: Annotated[Optional[Implementation], StrictField(description='a dictionary describing the server implementation')] = None class-attribute instance-attribute

last_id: Annotated[Optional[str], StrictField(description='a string containing the last ID returned')] = None class-attribute instance-attribute

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

more_data_available: Annotated[bool, StrictField(description='`false` if the response contains all data for the request (e.g., a request issued to a single entry endpoint, or a `filter` query at the last page of a paginated response) and `true` if the response is incomplete in the sense that multiple objects match the request, and not all of them have been included in the response (e.g., a query with multiple pages that is not at the last page).')] instance-attribute

optimade_schema: Annotated[Optional[jsonapi.JsonLinkType], StrictField(alias=schema, description='A [JSON API links object](http://jsonapi.org/format/1.0/#document-links) that points to a schema for the response.\nIf it is a string, or a dictionary containing no `meta` field, the provided URL MUST point at an [OpenAPI](https://swagger.io/specification/) schema.\nIt is possible that future versions of this specification allows for alternative schema types.\nHence, if the `meta` field of the JSON API links object is provided and contains a field `schema_type` that is not equal to the string `OpenAPI` the client MUST not handle failures to parse the schema or to validate the response against the schema as errors.')] = None class-attribute instance-attribute

provider: Annotated[Optional[Provider], StrictField(description='information on the database provider of the implementation.')] = None class-attribute instance-attribute

query: Annotated[ResponseMetaQuery, StrictField(description='Information on the Query that was requested')] instance-attribute

response_message: Annotated[Optional[str], StrictField(description='response string from the server')] = None class-attribute instance-attribute

time_stamp: Annotated[Optional[datetime], StrictField(description='A timestamp containing the date and time at which the query was executed.')] = None class-attribute instance-attribute

warnings: Annotated[Optional[list[Warnings]], StrictField(description='A list of warning resource objects representing non-critical errors or warnings.\nA warning resource object is defined similarly to a [JSON API error object](http://jsonapi.org/format/1.0/#error-objects), but MUST also include the field `type`, which MUST have the value `"warning"`.\nThe field `detail` MUST be present and SHOULD contain a non-critical message, e.g., reporting unrecognized search attributes or deprecated features.\nThe field `status`, representing a HTTP response status code, MUST NOT be present for a warning resource object.\nThis is an exclusive field for error resource objects.', uniqueItems=True)] = None class-attribute instance-attribute

StructureResource

Bases: EntryResource

Representing a structure.

Source code in optimade/models/structures.py
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
class StructureResource(EntryResource):
    """Representing a structure."""

    type: Annotated[
        Literal["structures"],
        StrictField(
            description="""The name of the type of an entry.

- **Type**: string.

- **Requirements/Conventions**:
    - **Support**: MUST be supported by all implementations, MUST NOT be `null`.
    - **Query**: MUST be a queryable property with support for all mandatory filter features.
    - **Response**: REQUIRED in the response.
    - MUST be an existing entry type.
    - The entry of type `<type>` and ID `<id>` MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.

- **Examples**:
    - `"structures"`""",
            pattern="^structures$",
            support=SupportLevel.MUST,
            queryable=SupportLevel.MUST,
        ),
    ] = "structures"

    attributes: StructureResourceAttributes

attributes: StructureResourceAttributes instance-attribute

id: Annotated[str, OptimadeField(description='An entry\'s ID as defined in section Definition of Terms.\n\n- **Type**: string.\n\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n\n- **Examples**:\n - `"db/1234567"`\n - `"cod/2000000"`\n - `"cod/2000000@1234567"`\n - `"nomad/L1234567890"`\n - `"42"`', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] instance-attribute

meta: Annotated[Optional[Meta], 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[Optional[EntryRelationships], StrictField(description='A dictionary containing references to other entries according to the description in section Relationships encoded as [JSON API Relationships](https://jsonapi.org/format/1.0/#document-resource-object-relationships).\nThe OPTIONAL human-readable description of the relationship MAY be provided in the `description` field inside the `meta` dictionary of the JSON API resource identifier object.')] = None class-attribute instance-attribute

type: Annotated[Literal['structures'], StrictField(description='The name of the type of an entry.\n\n- **Type**: string.\n\n- **Requirements/Conventions**:\n - **Support**: MUST be supported by all implementations, MUST NOT be `null`.\n - **Query**: MUST be a queryable property with support for all mandatory filter features.\n - **Response**: REQUIRED in the response.\n - MUST be an existing entry type.\n - The entry of type `<type>` and ID `<id>` MUST be returned in response to a request for `/<type>/<id>` under the versioned base URL.\n\n- **Examples**:\n - `"structures"`', pattern='^structures$', support=SupportLevel.MUST, queryable=SupportLevel.MUST)] = 'structures' class-attribute instance-attribute

StructureResponseMany

Bases: EntryResponseMany

Source code in optimade/models/responses.py
130
131
132
133
134
135
136
137
138
class StructureResponseMany(EntryResponseMany):
    data: Annotated[
        Union[list[StructureResource], list[dict[str, Any]]],
        StrictField(
            description="List of unique OPTIMADE structures entry resource objects.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ]

data: Annotated[Union[list[StructureResource], list[dict[str, Any]]], StrictField(description='List of unique OPTIMADE structures entry resource objects.', uniqueItems=True, union_mode=left_to_right)] instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

StructureResponseOne

Bases: EntryResponseOne

Source code in optimade/models/responses.py
120
121
122
123
124
125
126
127
class StructureResponseOne(EntryResponseOne):
    data: Annotated[
        Optional[Union[StructureResource, dict[str, Any]]],
        StrictField(
            description="A single structures entry resource.",
            union_mode="left_to_right",
        ),
    ]

data: Annotated[Optional[Union[StructureResource, dict[str, Any]]], StrictField(description='A single structures entry resource.', union_mode=left_to_right)] instance-attribute

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

included: Annotated[Optional[Union[list[EntryResource], list[dict[str, Any]]]], StrictField(description='A list of unique included OPTIMADE entry resources.', uniqueItems=True, union_mode=left_to_right)] = None class-attribute instance-attribute

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

Success

Bases: Response

errors are not allowed

Source code in optimade/models/optimade_json.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
class Success(jsonapi.Response):
    """errors are not allowed"""

    meta: Annotated[
        ResponseMeta,
        StrictField(description="A meta object containing non-standard information"),
    ]

    @model_validator(mode="after")
    def either_data_meta_or_errors_must_be_set(self) -> "Success":
        """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
        required_fields = ("data", "meta")
        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."
            )

        # errors MUST be skipped
        if self.errors or "errors" in self.model_fields_set:
            raise ValueError("'errors' MUST be skipped for a successful response.")

        return self

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

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

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

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

meta: Annotated[ResponseMeta, StrictField(description='A meta object containing non-standard information')] instance-attribute

model_config = ConfigDict(json_encoders={datetime: lambda : 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()

Overwriting the existing validation function, since 'errors' MUST NOT be set.

Source code in optimade/models/optimade_json.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> "Success":
    """Overwriting the existing validation function, since 'errors' MUST NOT be set."""
    required_fields = ("data", "meta")
    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."
        )

    # errors MUST be skipped
    if self.errors or "errors" in self.model_fields_set:
        raise ValueError("'errors' MUST be skipped for a successful response.")

    return self

StrictField(default=PydanticUndefined, *, description=None, **kwargs)

A wrapper around pydantic.Field that does the following:

  • Forbids any "extra" keys that would be passed to pydantic.Field, except those used elsewhere to modify the schema in-place, e.g. "uniqueItems", "pattern" and those added by OptimadeField, e.g. "unit", "queryable" and "sortable".
  • Emits a warning when no description is provided.

Parameters:

Name Type Description Default
default Any

The only non-keyword argument allowed for Field.

PydanticUndefined
description Optional[str]

The description of the Field; if this is not specified then a UserWarning will be emitted.

None
**kwargs Any

Extra keyword arguments to be passed to Field.

{}

Raises:

Type Description
RuntimeError

If **kwargs contains a key not found in the function signature of Field, or in the extensions used by models in this package (see above).

Returns:

Type Description
Any

The pydantic Field.

Source code in optimade/models/utils.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 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
110
111
112
113
114
115
116
117
118
119
def StrictField(
    default: "Any" = PydanticUndefined,
    *,
    description: Optional[str] = None,
    **kwargs: "Any",
) -> Any:
    """A wrapper around `pydantic.Field` that does the following:

    - Forbids any "extra" keys that would be passed to `pydantic.Field`,
      except those used elsewhere to modify the schema in-place,
      e.g. "uniqueItems", "pattern" and those added by OptimadeField, e.g.
      "unit", "queryable" and "sortable".
    - Emits a warning when no description is provided.

    Arguments:
        default: The only non-keyword argument allowed for Field.
        description: The description of the `Field`; if this is not
            specified then a `UserWarning` will be emitted.
        **kwargs: Extra keyword arguments to be passed to `Field`.

    Raises:
        RuntimeError: If `**kwargs` contains a key not found in the
            function signature of `Field`, or in the extensions used
            by models in this package (see above).

    Returns:
        The pydantic `Field`.

    """
    allowed_schema_and_field_keys = ["pattern"]

    allowed_keys = [
        "pattern",
        "uniqueItems",
    ] + OPTIMADE_SCHEMA_EXTENSION_KEYS
    _banned = [k for k in kwargs if k not in set(_PYDANTIC_FIELD_KWARGS + allowed_keys)]

    if _banned:
        raise RuntimeError(
            f"Not creating StrictField({default!r}, **{kwargs!r}) with "
            f"forbidden keywords {_banned}."
        )

    # Handle description
    if description is None:
        warnings.warn(
            f"No description provided for StrictField specified by {default!r}, "
            f"**{kwargs!r}."
        )
    else:
        kwargs["description"] = description

    # OPTIMADE schema extensions
    json_schema_extra: dict[str, Any] = kwargs.pop("json_schema_extra", {})

    # Go through all JSON Schema keys and add them to the json_schema_extra.
    for key in allowed_keys:
        if key not in kwargs:
            continue

        # If they are OPTIMADE schema extensions, add them with the OPTIMADE prefix.
        schema_key = (
            f"{OPTIMADE_SCHEMA_EXTENSION_PREFIX}{key}"
            if key in OPTIMADE_SCHEMA_EXTENSION_KEYS
            else key
        )

        for key_variant in (key, schema_key):
            if key_variant in json_schema_extra:
                if json_schema_extra.pop(key_variant) != kwargs[key]:
                    raise RuntimeError(
                        f"Conflicting values for {key} in json_schema_extra and kwargs."
                    )

        json_schema_extra[schema_key] = (
            kwargs[key] if key in allowed_schema_and_field_keys else kwargs.pop(key)
        )

    kwargs["json_schema_extra"] = json_schema_extra

    return Field(default, **kwargs)