httk.serve.optimade¶
Public generic OPTIMADE serving and query APIs.
Submodules¶
Exceptions¶
Represent an OPTIMADE response error. |
|
Represent a filter translation failure with an HTTP response contract. |
Classes¶
Bind a store to the OPTIMADE entry endpoints it serves. |
|
Describe one queryable source behind an OPTIMADE entry endpoint. |
|
Provide a store over dictionary rows. |
|
Serve one data federation per OPTIMADE entry type. |
|
Represent an endpoint response for serialization by the web layer. |
|
Configure a served OPTIMADE database. |
|
Configure an OPTIMADE index meta-database. |
|
Represent an incoming OPTIMADE request from the web layer. |
|
Represent validated URL query parameters of an OPTIMADE request. |
|
Represent the result of validating a |
Functions¶
|
Create an ASGI application serving an OPTIMADE API for a backend or store. |
|
Create an ASGI application for an OPTIMADE index meta-database. |
|
Serve an OPTIMADE API for a backend or entry store with a development server. |
|
Build a |
|
Build a lazy OPTIMADE adapter from every described family in one store. |
|
Build a lazy store-backed adapter from durable entry sources. |
Return the registered entry-provider factories keyed by their registered name. |
|
|
Process one OPTIMADE query. |
Package Contents¶
- httk.serve.optimade.create_asgi_app(adapter, config=None, *, baseurl=None, debug=False, report_level='warning', report_context_levels=None)[source]¶
Create an ASGI application serving an OPTIMADE API for a backend or store.
An absent
baseurlmakes the application derive a mount-aware URL from the request. An explicit value is authoritative.- Parameters:
adapter (httk.serve.optimade.model.results.OptimadeAdapter | httk.store.EntryStore) – Backend providing the served schema/query callback, or an entry store whose configured OPTIMADE families are discovered lazily.
config (httk.serve.optimade.model.config.OptimadeConfig | None) – Optional service configuration.
baseurl (str | None) – Public API base URL, or
Nonefor request-based derivation.debug (bool) – Enable application and backend diagnostics.
report_level (str | int) – Minimum report level collected per request.
report_context_levels (collections.abc.Mapping[str, str | int] | None) – Context-specific report levels.
- Returns:
Configured serving application.
- Return type:
- httk.serve.optimade.create_index_asgi_app(config, *, baseurl=None, debug=False, report_level='warning', report_context_levels=None)[source]¶
Create an ASGI application for an OPTIMADE index meta-database.
The index serves only discovery, links, and unversioned version negotiation. It has no backend adapter and performs no query calls. The supplied configuration is retained as the response metadata source; the composed application’s caller owns its lifetime and configuration.
- Parameters:
config (httk.serve.optimade.model.config.OptimadeIndexConfig) – Validated index metadata and configured database links.
baseurl (str | None) – Authoritative public index URL, or
Nonefor mount-aware derivation from each request.debug (bool) – Enable Starlette diagnostics.
report_level (str | int) – Minimum report level collected per request.
report_context_levels (collections.abc.Mapping[str, str | int] | None) – Context-specific report levels.
- Returns:
Configured serving application.
- Raises:
TypeError – If
configis not anOptimadeIndexConfig.- Return type:
- httk.serve.optimade.serve(adapter, config=None, *, host='127.0.0.1', port=8080, baseurl=None, debug=False, report_level='warning', report_context_levels=None)[source]¶
Serve an OPTIMADE API for a backend or entry store with a development server.
- Parameters:
adapter (httk.serve.optimade.model.results.OptimadeAdapter | httk.store.EntryStore) – Backend providing the served schema/query callback, or an entry store whose configured OPTIMADE families are discovered lazily.
config (httk.serve.optimade.model.config.OptimadeConfig | None) – Optional service configuration.
host (str) – Interface or hostname to bind.
port (int) – TCP port to bind.
baseurl (str | None) – Public API base URL, or
Noneto derive the local URL.debug (bool) – Enable application and backend diagnostics.
report_level (str | int) – Minimum report level collected per request.
report_context_levels (collections.abc.Mapping[str, str | int] | None) – Context-specific report levels.
- class httk.serve.optimade.BackendAdapter[source]¶
Bind a store to the OPTIMADE entry endpoints it serves.
sourcesmaps entry endpoint names (e.g.'structures') to the sources queried for that endpoint; an endpoint with several sources (e.g. several calculation result types) is queried across all of them.schemais required: it declares the served entry types and properties.field_handlersmaps each entry type to its filter-handler table. When omitted (left empty) it is derived fromschemaviasimple_property_handlers(), using an identity property-key map (each property is filtered against a backend field of the same name); a backend whose field names differ, or that wants finer control, supplies its own tables instead.- Parameters:
store – Store implementing the neutral query protocol.
sources – Queryable sources keyed by entry endpoint.
schema – Required schema describing served entries and properties.
field_handlers – Optional filter handlers keyed by entry endpoint.
- store: httk.store.query.Store¶
- field_handlers: collections.abc.Mapping[str, httk.store.query.optimade_filters.HandlerTable]¶
- class httk.serve.optimade.EntrySource[source]¶
Describe one queryable source behind an OPTIMADE entry endpoint.
targetis what gets passed tosearcher.variable();fieldsmaps OPTIMADE response-field names to extractors applied to matched row objects.relationships, when set, is an extractor mapping a matched row to a dictionary keyed by related entry type, each value a list of{'id': str, 'description': str?, 'role': str?}dictionaries.sort_keysmaps response-field names to the backend field names to sort on.property_metadatamaps response-field names to extractors returning the per-property metadata dictionary for a matched row (orNonewhen there is no metadata for that row).- Parameters:
target – Store-specific target passed to
searcher.variable.fields – Response-field extractors applied to matched rows.
sort_keys – Response-field to backend-sort-field mappings.
relationships – Optional extractor for related-resource data.
property_metadata – Optional per-property metadata extractors.
- target: Any¶
- fields: collections.abc.Mapping[str, FieldExtractor]¶
- sort_keys: collections.abc.Mapping[str, str]¶
- relationships: FieldExtractor | None = None¶
- property_metadata: collections.abc.Mapping[str, FieldExtractor]¶
- class httk.serve.optimade.InMemoryStore(tables)[source]¶
Provide a store over dictionary rows.
- tables¶
- searcher(*, as_of=None)[source]¶
Create a searcher over this store’s tables.
- Parameters:
as_of (object) – Optional historic timestamp cutoff; unsupported here.
- Returns:
Fresh in-memory searcher.
- Raises:
ValueError – If a historic cutoff is requested.
- Return type:
- class httk.serve.optimade.StoredBackendAdapter[source]¶
Serve one data federation per OPTIMADE entry type.
- Parameters:
federations – Durable federations keyed by entry endpoint.
schema – Schema describing the federations’ served entries.
- federations: collections.abc.Mapping[str, Any]¶
- snapshot_cutoff_ns(entry_type, now_ns)[source]¶
Return the resolution-aware snapshot cutoff for one entry type.
- httk.serve.optimade.adapter_from_providers(providers, **options)[source]¶
Build a
BackendAdapterserving the given entry providers.Every provider’s
entry_types()become served entry types (described by theirEntryTypeDefinition), itsproperty_keys()name the served subset and drive both the filter handlers (viasimple_property_handlers()) and the response-field extractors, and itsrecords()are loaded into anInMemoryStore. Every served property MUST be described by the entry type’s definition (a custom property must therefore live in anextended()definition); aValueErrornames any offender. All served properties beyondid/typeare marked default-response. Extra keywordoptions(e.g.sortable,recognized_prefixes) are forwarded tobuild_served_schema(); every served property is sortable-capable, since the provider’s property-key map is passed through as the source’ssort_keys.Declared relationships (
relationships()) are fully auto-wired for serving and filtering: for each entry type with declared relationships, a synthetic__rel_<related_type>id-list field is materialized on EVERY row of that entry type (an empty list when the row has no related entries of that type, so inverse set semantics are well-defined), and a'<related_type>.id'entry built withrelationship_id_handler()is merged into the entry type’s derived filter-handler table (never overwriting an entry already present, mirroring howBackendAdapterrespects explicitly supplied handler tables).<related_type>.id HAS ...filters — and, through the related-property resolver oftranslate_filter(), depth-1 relationship-property filters such asreferences.doi CONTAINS "10.1"— therefore work without any hand-wiring.A provider’s reverse relationships (
EntryProvider.reverse_relationships()) are consumed too: their target-keyed related entries are append-merged into each served target entry’s relationships (never clobbering the forward entries), so a derived reverse edge is served on the entry it points at.- Parameters:
providers (collections.abc.Iterable[httk.core.EntryProvider]) – Generic entry providers supplying definitions, keys, records, and relationships.
**options (Any) – Schema options forwarded to
build_served_schema().
- Returns:
Fully wired in-memory backend adapter.
- Raises:
ValueError – If provider keys or served properties are invalid.
- Return type:
- httk.serve.optimade.adapter_from_store(store, **options)[source]¶
Build a lazy OPTIMADE adapter from every described family in one store.
Families declared without an entry-type definition are deliberately ignored. This lets application-specific records, such as DSP publication declarations, coexist with OPTIMADE records in one durable layout.
- Parameters:
store (httk.store.EntryStore) – Entry store whose configured layout is discovered.
**options (Any) – Schema options forwarded to
adapter_from_stores().
- Returns:
Lazy adapter over all configured OPTIMADE families.
- Raises:
TypeError – If
storedoes not implementEntryStore.ValueError – If the store contains no OPTIMADE-described family.
- Return type:
- httk.serve.optimade.adapter_from_stores(sources, **options)[source]¶
Build a lazy store-backed adapter from durable entry sources.
Sources with the same exact logical family are federated under one entry endpoint. The data layer owns all source/backing traversal and global pagination; this adapter advertises the family’s definition and turns only the returned page into OPTIMADE result rows.
- Parameters:
sources (collections.abc.Sequence[httk.store.backend.sql.StoredEntrySource]) – Durable entry sources to federate by entry type.
**options (Any) – Schema options forwarded to
build_served_schema(), e.g.default_includes(per served entry type, the served entry types to include by default on single-entry requests; always unioned withreferences).
- Returns:
Lazy adapter over the supplied durable sources.
- Raises:
ValueError – If sources conflict or expose incomplete sort mappings.
TypeError – If a source is not a stored entry source.
- Return type:
- httk.serve.optimade.providers_from_registry()[source]¶
Return the registered entry-provider factories keyed by their registered name.
Resolves each factory registered via
httk.core.register_entry_provider()(throughhttk.registry.*self-registration) into a callable. Providers need data, so applications instantiate them:providers_from_registry()["atomistic-structures"](data).- Returns:
Registered provider factories keyed by registry name.
- Return type:
dict[str, collections.abc.Callable[…, httk.core.EntryProvider]]
- httk.serve.optimade.process(request, query_function, version, config, schema, *, snapshot_cutoff_ns=None, debug=False)[source]¶
Process one OPTIMADE query.
requestcarries the incoming request; onlybaseurlandrepresentationmust be set, missing information is derived fromrepresentation.query_functionis the callback used to execute entry queries against the backend.schemadescribes the served entry types and properties.- Parameters:
request (httk.serve.optimade.model.request.RawRequest) – Raw request to validate and dispatch.
query_function (httk.serve.optimade.model.results.QueryFunction) – Backend callback used for entry queries.
version (str) – API version selected for the request.
config (httk.serve.optimade.model.config.OptimadeConfig) – Service response configuration.
schema (httk.serve.optimade.schema.served.ServedSchema) – Explicit served schema for endpoint validation.
snapshot_cutoff_ns (SnapshotCutoff | None) – Optional stored-backend snapshot capability.
debug (bool) – Enable backend diagnostics.
- Returns:
Endpoint response before web serialization.
- Raises:
httk.serve.optimade.model.errors.OptimadeError – If request validation or endpoint processing fails.
- Return type:
- class httk.serve.optimade.EndpointResponse[source]¶
Represent an endpoint response for serialization by the web layer.
Either
json_response(a JSON:API document) orcontent(a raw body) is set.- Parameters:
response_code – HTTP status code.
response_msg – HTTP status title.
content_type – Response media type.
encoding – Response character encoding.
content – Raw response body, when the response is not JSON.
json_response – JSON:API response document, when the response is JSON.
- class httk.serve.optimade.OptimadeConfig[source]¶
Configure a served OPTIMADE database.
implementationextends/overrides the fields of themeta->implementationdictionary (e.g.issue_tracker,source_url,maintainer).database,schema_url, andrequest_delaypopulate the corresponding optionalmetafields (OPTIMADE v1.2+) when set.license,available_licenses, andavailable_licenses_for_entriespopulate the corresponding optional base-info attributes when set.- Parameters:
provider – Provider metadata for the OPTIMADE response envelope.
links – Provider links exposed by the
/linksendpoint.implementation – Implementation metadata merged into response metadata.
database – Optional database metadata for response metadata.
schema_url – URL of the served schema, when one is available.
request_delay – Optional advertised request delay.
license – License metadata exposed by the base-info endpoint.
available_licenses – Licenses advertised for the service.
available_licenses_for_entries – Licenses advertised for entries.
page_limit_max – Largest
page_limitaccepted; larger requests get a 403.partial_data_chunk_size – Number of outer items emitted per partial-data page.
cors_origins – Exact browser origins allowed to make cross-origin requests.
- Raises:
ValueError – If
page_limit_maxis not an integer >= 1.
- exception httk.serve.optimade.OptimadeError(message, response_code, response_message, longmsg=None)[source]¶
Bases:
ExceptionRepresent an OPTIMADE response error.
- Parameters:
- response_code¶
- response_msg¶
- content¶
- class httk.serve.optimade.OptimadeIndexConfig[source]¶
Bases:
OptimadeConfigConfigure an OPTIMADE index meta-database.
The links are the configured databases advertised by the index. Exactly one must have
link_type == "root"; child links are the databases that may be selected as the index’s default relationship. The regularOptimadeConfigremains a non-index service configuration.- Parameters:
default_link_id – Identifier of the default configured child link, or
Nonewhen the index has no default.- Raises:
ValueError – If configured links do not satisfy the links schema or the root/default-link constraints.
- class httk.serve.optimade.RawRequest[source]¶
Represent an incoming OPTIMADE request from the web layer.
Only
baseurlandrepresentationare mandatory; missing information is derived fromrepresentationduring validation.- Parameters:
baseurl – Base URL used when generating response links.
representation – Request path and query representation.
relurl – Relative request URL, when supplied by the web layer.
querystr – Raw query string.
query – Parsed query parameters.
endpoint – Preselected endpoint, when supplied by the caller.
request_id – Preselected entry identifier, when supplied by the caller.
version – API version declared by the caller.
- exception httk.serve.optimade.TranslatorError(message, response_code, response_message, longmsg=None)[source]¶
Bases:
OptimadeErrorRepresent a filter translation failure with an HTTP response contract.
- class httk.serve.optimade.ValidatedParameters[source]¶
Represent validated URL query parameters of an OPTIMADE request.
- Parameters:
response_format – Requested response format.
page_limit – Maximum number of entries in a page.
page_offset – Number of matching entries to skip.
response_fields – Comma-separated requested response fields.
filter – Raw OPTIMADE filter expression.
sort – Raw OPTIMADE sort expression.
include – Raw related-entry inclusion request.
as_of – Nanosecond timestamp cutoff for timestamp-capable stored sources; timestamp-disabled sources may serve current state and generic providers ignore it.
dimension_slices – Requested slices keyed by dimension name.
- dimension_slices: dict[str, RequestedSlice]¶
- class httk.serve.optimade.ValidatedRequest[source]¶
Represent the result of validating a
RawRequest.- Parameters:
baseurl – Base URL used when generating response links.
representation – Original request representation.
endpoint – Validated endpoint name.
version – Validated OPTIMADE version.
query – Validated query parameters.
url_version – Version segment present in the request URL.
request_id – Validated entry identifier.
revisions – Whether this is a stored revision request.
alternatives – Whether this is a stored alternative request.
request_immutable_id – Immutable revision identifier for a single revision request.
endpoint_path – Exact entry path used for collection-link generation.
recognized_response_fields – Requested fields known to the schema.
unrecognized_response_fields – Requested fields not known to the schema.
sort_fields – Validated sort fields and directions.
include_paths – Validated related-entry paths.
property_metadata_requested – Whether property metadata was requested.
partial_data_parts – Entry, identifier, and property for partial data.
partial_data_offset – Offset into a partial-data response.
warnings – Warnings collected while processing the request.
- query: ValidatedParameters¶