Skip to content

queries

Pydantic models/schemas for the Queries resource.

QUERY_PARAMETERS: QueryParameters = {'annotations': {name: FieldInfo.from_annotation(parameter.annotation)for (name, parameter) in inspect.signature(EntryListingQueryParams).parameters.items()}, 'defaults': EntryListingQueryParams()} module-attribute

Entry listing URL query parameters from the optimade package (EntryListingQueryParams).

EndpointEntryType

Bases: Enum

Entry endpoint resource types, mapping to their pydantic models from the optimade package.

Source code in optimade_gateway/models/queries.py
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
class EndpointEntryType(Enum):
    """Entry endpoint resource types, mapping to their pydantic models from the
    `optimade` package."""

    REFERENCES = "references"
    STRUCTURES = "structures"

    def get_resource_model(self) -> ReferenceResource | StructureResource:
        """Get the matching pydantic model for a resource."""
        return {
            "references": ReferenceResource,
            "structures": StructureResource,
        }[self.value]

    def get_response_model(
        self, single: bool = False
    ) -> (
        ReferenceResponseMany
        | ReferenceResponseOne
        | StructureResponseMany
        | StructureResponseOne
    ):
        """Get the matching pydantic model for a successful response."""
        if single:
            return {
                "references": ReferenceResponseOne,
                "structures": StructureResponseOne,
            }[self.value]
        return {
            "references": ReferenceResponseMany,
            "structures": StructureResponseMany,
        }[self.value]

REFERENCES = 'references' class-attribute instance-attribute

STRUCTURES = 'structures' class-attribute instance-attribute

get_resource_model()

Get the matching pydantic model for a resource.

Source code in optimade_gateway/models/queries.py
55
56
57
58
59
60
def get_resource_model(self) -> ReferenceResource | StructureResource:
    """Get the matching pydantic model for a resource."""
    return {
        "references": ReferenceResource,
        "structures": StructureResource,
    }[self.value]

get_response_model(single=False)

Get the matching pydantic model for a successful response.

Source code in optimade_gateway/models/queries.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def get_response_model(
    self, single: bool = False
) -> (
    ReferenceResponseMany
    | ReferenceResponseOne
    | StructureResponseMany
    | StructureResponseOne
):
    """Get the matching pydantic model for a successful response."""
    if single:
        return {
            "references": ReferenceResponseOne,
            "structures": StructureResponseOne,
        }[self.value]
    return {
        "references": ReferenceResponseMany,
        "structures": StructureResponseMany,
    }[self.value]

EntryResource

Bases: EntryResource

Entry Resource ensuring datetimes are not naive.

Source code in optimade_gateway/models/queries.py
210
211
212
213
214
215
216
217
218
219
220
221
class EntryResource(OptimadeEntryResource):
    """Entry Resource ensuring datetimes are not naive."""

    @field_validator("attributes", mode="after")
    @classmethod
    def ensure_non_naive_datetime(
        cls, value: EntryResourceAttributes
    ) -> EntryResourceAttributes:
        """Set timezone to UTC if datetime is naive."""
        if value.last_modified and value.last_modified.tzinfo is None:
            value.last_modified = value.last_modified.replace(tzinfo=timezone.utc)
        return value

ensure_non_naive_datetime(value) classmethod

Set timezone to UTC if datetime is naive.

Source code in optimade_gateway/models/queries.py
213
214
215
216
217
218
219
220
221
@field_validator("attributes", mode="after")
@classmethod
def ensure_non_naive_datetime(
    cls, value: EntryResourceAttributes
) -> EntryResourceAttributes:
    """Set timezone to UTC if datetime is naive."""
    if value.last_modified and value.last_modified.tzinfo is None:
        value.last_modified = value.last_modified.replace(tzinfo=timezone.utc)
    return value

GatewayQueryResponse

Bases: Response

Response from a Gateway Query.

Source code in optimade_gateway/models/queries.py
224
225
226
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
257
258
259
260
261
262
263
class GatewayQueryResponse(Response):
    """Response from a Gateway Query."""

    data: Annotated[
        dict[str, list[EntryResource] | list[dict[str, Any]]],
        StrictField(uniqueItems=True, description="Outputted Data."),
    ]

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

    errors: Annotated[
        list[OptimadeError] | None,
        StrictField(
            description=(
                "A list of OPTIMADE-specific JSON API error objects, where the field "
                "detail MUST be present."
            ),
            uniqueItems=True,
        ),
    ] = []  # noqa: RUF012

    included: Annotated[
        list[EntryResource] | list[dict[str, Any]] | None,
        StrictField(
            description="A list of unique included OPTIMADE entry resources.",
            uniqueItems=True,
            union_mode="left_to_right",
        ),
    ] = None

    @model_validator(mode="after")
    def either_data_meta_or_errors_must_be_set(self) -> GatewayQueryResponse:
        """Overwrite `either_data_meta_or_errors_must_be_set`.

        `errors` should be allowed to be present always for this special response.
        """
        return self

data: Annotated[dict[str, list[EntryResource] | list[dict[str, Any]]], StrictField(uniqueItems=True, description='Outputted Data.')] instance-attribute

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

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

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

either_data_meta_or_errors_must_be_set()

Overwrite either_data_meta_or_errors_must_be_set.

errors should be allowed to be present always for this special response.

Source code in optimade_gateway/models/queries.py
257
258
259
260
261
262
263
@model_validator(mode="after")
def either_data_meta_or_errors_must_be_set(self) -> GatewayQueryResponse:
    """Overwrite `either_data_meta_or_errors_must_be_set`.

    `errors` should be allowed to be present always for this special response.
    """
    return self

OptimadeQueryParameters

Bases: BaseModel

Common OPTIMADE entry listing endpoint query parameters.

Source code in optimade_gateway/models/queries.py
 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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
class OptimadeQueryParameters(BaseModel):
    """Common OPTIMADE entry listing endpoint query parameters."""

    filter: Annotated[
        str | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["filter"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].filter

    response_format: Annotated[
        str | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["response_format"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].response_format

    email_address: Annotated[
        EmailStr | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["email_address"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].email_address

    response_fields: Annotated[
        str | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["response_fields"].description,
            pattern=QUERY_PARAMETERS["annotations"]["response_fields"]
            .metadata[0]
            .pattern,
        ),
    ] = QUERY_PARAMETERS["defaults"].response_fields

    sort: Annotated[
        str | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["sort"].description,
            pattern=QUERY_PARAMETERS["annotations"]["sort"].metadata[0].pattern,
        ),
    ] = QUERY_PARAMETERS["defaults"].sort

    page_limit: Annotated[
        int | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["page_limit"].description,
            ge=QUERY_PARAMETERS["annotations"]["page_limit"].metadata[0].ge,
        ),
    ] = QUERY_PARAMETERS["defaults"].page_limit

    page_offset: Annotated[
        int | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["page_offset"].description,
            ge=QUERY_PARAMETERS["annotations"]["page_offset"].metadata[0].ge,
        ),
    ] = QUERY_PARAMETERS["defaults"].page_offset

    page_number: Annotated[
        int | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["page_number"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].page_number

    page_cursor: Annotated[
        int | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["page_cursor"].description,
            ge=QUERY_PARAMETERS["annotations"]["page_cursor"].metadata[0].ge,
        ),
    ] = QUERY_PARAMETERS["defaults"].page_cursor

    page_above: Annotated[
        int | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["page_above"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].page_above

    page_below: Annotated[
        int | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["page_below"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].page_below

    include: Annotated[
        str | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["include"].description,
        ),
    ] = QUERY_PARAMETERS["defaults"].include

    api_hint: Annotated[
        str | None,
        Field(
            description=QUERY_PARAMETERS["annotations"]["api_hint"].description,
            pattern=QUERY_PARAMETERS["annotations"]["api_hint"].metadata[0].pattern,
        ),
    ] = QUERY_PARAMETERS["defaults"].api_hint

api_hint: Annotated[str | None, Field(description=QUERY_PARAMETERS['annotations']['api_hint'].description, pattern=QUERY_PARAMETERS['annotations']['api_hint'].metadata[0].pattern)] = QUERY_PARAMETERS['defaults'].api_hint class-attribute instance-attribute

email_address: Annotated[EmailStr | None, Field(description=QUERY_PARAMETERS['annotations']['email_address'].description)] = QUERY_PARAMETERS['defaults'].email_address class-attribute instance-attribute

filter: Annotated[str | None, Field(description=QUERY_PARAMETERS['annotations']['filter'].description)] = QUERY_PARAMETERS['defaults'].filter class-attribute instance-attribute

include: Annotated[str | None, Field(description=QUERY_PARAMETERS['annotations']['include'].description)] = QUERY_PARAMETERS['defaults'].include class-attribute instance-attribute

page_above: Annotated[int | None, Field(description=QUERY_PARAMETERS['annotations']['page_above'].description)] = QUERY_PARAMETERS['defaults'].page_above class-attribute instance-attribute

page_below: Annotated[int | None, Field(description=QUERY_PARAMETERS['annotations']['page_below'].description)] = QUERY_PARAMETERS['defaults'].page_below class-attribute instance-attribute

page_cursor: Annotated[int | None, Field(description=QUERY_PARAMETERS['annotations']['page_cursor'].description, ge=QUERY_PARAMETERS['annotations']['page_cursor'].metadata[0].ge)] = QUERY_PARAMETERS['defaults'].page_cursor class-attribute instance-attribute

page_limit: Annotated[int | None, Field(description=QUERY_PARAMETERS['annotations']['page_limit'].description, ge=QUERY_PARAMETERS['annotations']['page_limit'].metadata[0].ge)] = QUERY_PARAMETERS['defaults'].page_limit class-attribute instance-attribute

page_number: Annotated[int | None, Field(description=QUERY_PARAMETERS['annotations']['page_number'].description)] = QUERY_PARAMETERS['defaults'].page_number class-attribute instance-attribute

page_offset: Annotated[int | None, Field(description=QUERY_PARAMETERS['annotations']['page_offset'].description, ge=QUERY_PARAMETERS['annotations']['page_offset'].metadata[0].ge)] = QUERY_PARAMETERS['defaults'].page_offset class-attribute instance-attribute

response_fields: Annotated[str | None, Field(description=QUERY_PARAMETERS['annotations']['response_fields'].description, pattern=QUERY_PARAMETERS['annotations']['response_fields'].metadata[0].pattern)] = QUERY_PARAMETERS['defaults'].response_fields class-attribute instance-attribute

response_format: Annotated[str | None, Field(description=QUERY_PARAMETERS['annotations']['response_format'].description)] = QUERY_PARAMETERS['defaults'].response_format class-attribute instance-attribute

sort: Annotated[str | None, Field(description=QUERY_PARAMETERS['annotations']['sort'].description, pattern=QUERY_PARAMETERS['annotations']['sort'].metadata[0].pattern)] = QUERY_PARAMETERS['defaults'].sort class-attribute instance-attribute

QueryCreate

Bases: EntryResourceCreate, QueryResourceAttributes

Model for creating new Query resources in the MongoDB

Source code in optimade_gateway/models/queries.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
class QueryCreate(EntryResourceCreate, QueryResourceAttributes):
    """Model for creating new Query resources in the MongoDB"""

    state: Annotated[
        QueryState | None,
        Field(
            title=QueryResourceAttributes.model_fields["state"].title,
            description=QueryResourceAttributes.model_fields["state"].description,
            json_schema_extra=QueryResourceAttributes.model_fields[
                "state"
            ].json_schema_extra,
        ),
    ] = None  # type: ignore[assignment]
    endpoint: Annotated[
        EndpointEntryType | None,
        Field(
            title=QueryResourceAttributes.model_fields["endpoint"].title,
            description=QueryResourceAttributes.model_fields["endpoint"].description,
            json_schema_extra=QueryResourceAttributes.model_fields[
                "endpoint"
            ].json_schema_extra,
        ),
    ] = None  # type: ignore[assignment]

    @field_validator("query_parameters", mode="after")
    @classmethod
    def sort_not_supported(
        cls, value: OptimadeQueryParameters
    ) -> OptimadeQueryParameters:
        """Warn and reset value if `sort` is supplied."""
        if value.sort:
            warnings.warn(SortNotSupported())
            value.sort = None
        return value

endpoint: Annotated[EndpointEntryType | None, Field(title=QueryResourceAttributes.model_fields['endpoint'].title, description=QueryResourceAttributes.model_fields['endpoint'].description, json_schema_extra=QueryResourceAttributes.model_fields['endpoint'].json_schema_extra)] = None class-attribute instance-attribute

state: Annotated[QueryState | None, Field(title=QueryResourceAttributes.model_fields['state'].title, description=QueryResourceAttributes.model_fields['state'].description, json_schema_extra=QueryResourceAttributes.model_fields['state'].json_schema_extra)] = None class-attribute instance-attribute

sort_not_supported(value) classmethod

Warn and reset value if sort is supplied.

Source code in optimade_gateway/models/queries.py
470
471
472
473
474
475
476
477
478
479
@field_validator("query_parameters", mode="after")
@classmethod
def sort_not_supported(
    cls, value: OptimadeQueryParameters
) -> OptimadeQueryParameters:
    """Warn and reset value if `sort` is supplied."""
    if value.sort:
        warnings.warn(SortNotSupported())
        value.sort = None
    return value

QueryParameters

Bases: TypedDict

Type definition for QUERY_PARAMETERS.

Source code in optimade_gateway/models/queries.py
41
42
43
44
45
class QueryParameters(TypedDict):
    """Type definition for `QUERY_PARAMETERS`."""

    annotations: dict[str, FieldInfo]
    defaults: EntryListingQueryParams

annotations: dict[str, FieldInfo] instance-attribute

defaults: EntryListingQueryParams instance-attribute

QueryResource

Bases: EntryResource

OPTIMADE query resource for a gateway

Source code in optimade_gateway/models/queries.py
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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
class QueryResource(EntryResource):
    """OPTIMADE query resource for a gateway"""

    type: Annotated[
        Literal["queries"],
        Field(
            description="The name of the type of an entry.",
        ),
    ] = "queries"

    attributes: QueryResourceAttributes

    async def response_as_optimade(
        self,
        url: None | (
            urllib.parse.ParseResult | urllib.parse.SplitResult | StarletteURL | str
        ) = None,
    ) -> EntryResponseMany | ErrorResponse:
        """Return `attributes.response` as a valid OPTIMADE entry listing response.

        Note, this method disregards the state of the query and will simply return the
        query results as they currently are (if there are any at all).

        Parameters:
            url: Optionally, update the `meta.query.representation` value with this.

        Returns:
            A valid OPTIMADE entry-listing response according to the
            [OPTIMADE specification](https://github.com/Materials-Consortia/OPTIMADE/blob/master/optimade.rst#entry-listing-endpoints)
            or an error response, if errors were returned or occurred during the query.

        """
        from optimade.server.routers.utils import (
            meta_values,
        )

        async def _update_id(
            entry_: EntryResource | dict[str, Any], database_provider_: str
        ) -> EntryResource | dict[str, Any]:
            """Internal utility function to prepend the entries' `id` with
            `provider/database/`.

            Parameters:
                entry_: The entry as a model or a dictionary.
                database_provider_: `provider/database` string.

            Returns:
                The entry with an updated `id` value.

            """
            if isinstance(entry_, dict):
                _entry = deepcopy(entry_)
                _entry["id"] = f"{database_provider_}/{entry_['id']}"
                return _entry

            return entry_.model_copy(
                update={"id": f"{database_provider_}/{entry_.id}"},
                deep=True,
            ).model_dump(exclude_unset=True, exclude_none=True)

        if not self.attributes.response:
            # The query has not yet been initiated
            return ErrorResponse(
                errors=[
                    {
                        "detail": (
                            "Can not return as a valid OPTIMADE response as the query "
                            "has not yet been initialized."
                        ),
                        "id": "OPTIMADE_GATEWAY_QUERY_NOT_INITIALIZED",
                    }
                ],
                meta=meta_values(
                    url=url or f"/queries/{self.id}?",
                    data_returned=0,
                    data_available=0,
                    more_data_available=False,
                    schema=CONFIG.schema_url,
                ),
            )

        meta_ = self.attributes.response.meta

        if url:
            meta_ = meta_.model_dump(exclude_unset=True)
            for repeated_key in (
                "query",
                "api_version",
                "time_stamp",
                "provider",
                "implementation",
            ):
                meta_.pop(repeated_key, None)
            meta_ = meta_values(url=url, **meta_)

        # Error response
        if self.attributes.response.errors:
            return ErrorResponse(
                errors=self.attributes.response.errors,
                meta=meta_,
            )

        # Data response
        results = []
        for database_provider, entries in self.attributes.response.data.items():
            results.extend(
                [await _update_id(entry, database_provider) for entry in entries]
            )

        return self.attributes.endpoint.get_response_model()(
            data=results,
            meta=meta_,
            links=self.attributes.response.links,
        )

attributes: QueryResourceAttributes instance-attribute

type: Annotated[Literal['queries'], Field(description='The name of the type of an entry.')] = 'queries' class-attribute instance-attribute

response_as_optimade(url=None) async

Return attributes.response as a valid OPTIMADE entry listing response.

Note, this method disregards the state of the query and will simply return the query results as they currently are (if there are any at all).

Parameters:

Name Type Description Default
url None | ParseResult | SplitResult | URL | str

Optionally, update the meta.query.representation value with this.

None

Returns:

Type Description
EntryResponseMany | ErrorResponse

A valid OPTIMADE entry-listing response according to the

EntryResponseMany | ErrorResponse
EntryResponseMany | ErrorResponse

or an error response, if errors were returned or occurred during the query.

Source code in optimade_gateway/models/queries.py
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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
async def response_as_optimade(
    self,
    url: None | (
        urllib.parse.ParseResult | urllib.parse.SplitResult | StarletteURL | str
    ) = None,
) -> EntryResponseMany | ErrorResponse:
    """Return `attributes.response` as a valid OPTIMADE entry listing response.

    Note, this method disregards the state of the query and will simply return the
    query results as they currently are (if there are any at all).

    Parameters:
        url: Optionally, update the `meta.query.representation` value with this.

    Returns:
        A valid OPTIMADE entry-listing response according to the
        [OPTIMADE specification](https://github.com/Materials-Consortia/OPTIMADE/blob/master/optimade.rst#entry-listing-endpoints)
        or an error response, if errors were returned or occurred during the query.

    """
    from optimade.server.routers.utils import (
        meta_values,
    )

    async def _update_id(
        entry_: EntryResource | dict[str, Any], database_provider_: str
    ) -> EntryResource | dict[str, Any]:
        """Internal utility function to prepend the entries' `id` with
        `provider/database/`.

        Parameters:
            entry_: The entry as a model or a dictionary.
            database_provider_: `provider/database` string.

        Returns:
            The entry with an updated `id` value.

        """
        if isinstance(entry_, dict):
            _entry = deepcopy(entry_)
            _entry["id"] = f"{database_provider_}/{entry_['id']}"
            return _entry

        return entry_.model_copy(
            update={"id": f"{database_provider_}/{entry_.id}"},
            deep=True,
        ).model_dump(exclude_unset=True, exclude_none=True)

    if not self.attributes.response:
        # The query has not yet been initiated
        return ErrorResponse(
            errors=[
                {
                    "detail": (
                        "Can not return as a valid OPTIMADE response as the query "
                        "has not yet been initialized."
                    ),
                    "id": "OPTIMADE_GATEWAY_QUERY_NOT_INITIALIZED",
                }
            ],
            meta=meta_values(
                url=url or f"/queries/{self.id}?",
                data_returned=0,
                data_available=0,
                more_data_available=False,
                schema=CONFIG.schema_url,
            ),
        )

    meta_ = self.attributes.response.meta

    if url:
        meta_ = meta_.model_dump(exclude_unset=True)
        for repeated_key in (
            "query",
            "api_version",
            "time_stamp",
            "provider",
            "implementation",
        ):
            meta_.pop(repeated_key, None)
        meta_ = meta_values(url=url, **meta_)

    # Error response
    if self.attributes.response.errors:
        return ErrorResponse(
            errors=self.attributes.response.errors,
            meta=meta_,
        )

    # Data response
    results = []
    for database_provider, entries in self.attributes.response.data.items():
        results.extend(
            [await _update_id(entry, database_provider) for entry in entries]
        )

    return self.attributes.endpoint.get_response_model()(
        data=results,
        meta=meta_,
        links=self.attributes.response.links,
    )

QueryResourceAttributes

Bases: EntryResourceAttributes

Attributes for an OPTIMADE gateway query.

Source code in optimade_gateway/models/queries.py
266
267
268
269
270
271
272
273
274
275
276
277
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
class QueryResourceAttributes(EntryResourceAttributes):
    """Attributes for an OPTIMADE gateway query."""

    gateway_id: Annotated[
        str,
        Field(
            description="The OPTIMADE gateway ID for this query.",
        ),
    ]

    query_parameters: Annotated[
        OptimadeQueryParameters,
        Field(
            description=(
                "OPTIMADE query parameters for entry listing endpoints used for this "
                "query."
            ),
            json_schema_extra={
                "type": "object",
            },
        ),
    ]

    state: Annotated[
        QueryState,
        Field(
            description="Current state of Gateway Query.",
            title="State",
            json_schema_extra={
                "type": "enum",
            },
        ),
    ] = QueryState.CREATED

    response: Annotated[
        GatewayQueryResponse | None,
        Field(
            description="Response from gateway query.",
        ),
    ] = None

    endpoint: Annotated[
        EndpointEntryType,
        Field(
            description="The entry endpoint queried, e.g., 'structures'.",
            title="Endpoint",
            json_schema_extra={
                "type": "enum",
            },
        ),
    ] = EndpointEntryType.STRUCTURES

    @field_validator("endpoint", mode="after")
    @classmethod
    def only_allow_structures(cls, value: EndpointEntryType) -> EndpointEntryType:
        """Temporarily only allow queries to "structures" endpoints."""
        if value != EndpointEntryType.STRUCTURES:
            raise NotImplementedError(
                'OPTIMADE Gateway temporarily only supports queries to "structures" '
                'endpoints, i.e.: endpoint="structures"'
            )
        return value

endpoint: Annotated[EndpointEntryType, Field(description="The entry endpoint queried, e.g., 'structures'.", title='Endpoint', json_schema_extra={'type': 'enum'})] = EndpointEntryType.STRUCTURES class-attribute instance-attribute

gateway_id: Annotated[str, Field(description='The OPTIMADE gateway ID for this query.')] instance-attribute

query_parameters: Annotated[OptimadeQueryParameters, Field(description='OPTIMADE query parameters for entry listing endpoints used for this query.', json_schema_extra={'type': 'object'})] instance-attribute

response: Annotated[GatewayQueryResponse | None, Field(description='Response from gateway query.')] = None class-attribute instance-attribute

state: Annotated[QueryState, Field(description='Current state of Gateway Query.', title='State', json_schema_extra={'type': 'enum'})] = QueryState.CREATED class-attribute instance-attribute

only_allow_structures(value) classmethod

Temporarily only allow queries to "structures" endpoints.

Source code in optimade_gateway/models/queries.py
318
319
320
321
322
323
324
325
326
327
@field_validator("endpoint", mode="after")
@classmethod
def only_allow_structures(cls, value: EndpointEntryType) -> EndpointEntryType:
    """Temporarily only allow queries to "structures" endpoints."""
    if value != EndpointEntryType.STRUCTURES:
        raise NotImplementedError(
            'OPTIMADE Gateway temporarily only supports queries to "structures" '
            'endpoints, i.e.: endpoint="structures"'
        )
    return value

QueryState

Bases: Enum

Enumeration of possible states for a Gateway Query.

The states are enumerated here in the expected evolvement.

Source code in optimade_gateway/models/queries.py
198
199
200
201
202
203
204
205
206
207
class QueryState(Enum):
    """Enumeration of possible states for a Gateway Query.

    The states are enumerated here in the expected evolvement.
    """

    CREATED = "created"
    STARTED = "started"
    IN_PROGRESS = "in progress"
    FINISHED = "finished"

CREATED = 'created' class-attribute instance-attribute

FINISHED = 'finished' class-attribute instance-attribute

IN_PROGRESS = 'in progress' class-attribute instance-attribute

STARTED = 'started' class-attribute instance-attribute