Skip to content

API reference

Reference of the app's Python code, generated from its docstrings. For the HTTP API, see API and the Swagger UI of a deployment.

App

app

App factory, and entry point for development.

The image serves the app with Gunicorn (drs_filer.app:create_app(), see drs_filer.gunicorn_config); python -m drs_filer.app runs it with Flask's development server, for development only.

check_removed_sections

check_removed_sections() -> None

Fail on config sections of earlier versions, which would be ignored.

FOCA keeps sections that it doesn't know as untyped extra fields, so a config overlay of an earlier version would silently leave the defaults in place (e.g., the placeholder service info).

Raises:

Type Description
ValueError

The config has a section of an earlier version (cf. REMOVED_SECTIONS).

check_service_type

check_service_type() -> None

Fail on service info of another type than the API that the app serves.

GET /service-info serves DrsService (DRS 1.5.0), whose type.artifact is drs; FOCA validates the service info against the GA4GH Service schema only, so that other artifacts would fail every response instead of the start, and other groups or versions would describe another API to clients and registries.

Raises:

Type Description
ValueError

service_info.service.type isn't SERVICE_TYPE.

answer_cors_preflight

answer_cors_preflight() -> Response | None

Answer CORS preflight requests before the API operations do.

DRS defines OPTIONS operations (the authorization info of objects), which would get the preflight requests of browsers too (and fail for OPTIONS /objects, whose preflight has no body). These get Flask's default answer, with the CORS headers that FOCA adds (if CORS is enabled), as for paths without OPTIONS operations. Registered with before_request.

Returns:

Type Description
Response | None

Flask's default response to OPTIONS (200, with Allow) for

Response | None

preflight requests (OPTIONS with Origin and

Response | None

Access-Control-Request-Method) to known paths, None for other

Response | None

requests, which are routed as usual (unknown paths get 404).

create_app

create_app() -> App

Create the app from the config, and register the service info.

FOCA validates the config, including the app's own section (custom, against drs_filer.custom_config.CustomConfig) and the service info (service_info), so that invalid settings (e.g., character sets of identifiers given as expressions, or unknown keys) fail the start; so do sections of earlier versions (check_removed_sections()) and service info of another type than DRS (check_service_type()). The service info of the config (with the version of the package, unless set) then replaces the stored one. Whether access URLs and object reads need login is read from the patched specification, and logged (access_urls_need_login(), object_reads_need_login()). CORS preflight requests are answered before the API operations (answer_cors_preflight()). The config is the package's config.yaml, with the overlays of FOCA_CONFIG_OVERLAY merged into it by FOCA, if any (separated by :, in order; relative paths of overlays are relative to the working directory). FOCA resolves the relative paths of the API specifications against the package directory, whatever the working directory (e.g., of Gunicorn in the image). Gunicorn calls this in each worker, after forking (MongoDB clients must not be shared across forks).

Returns:

Type Description
App

Connexion app.

Raises:

Type Description
ValueError

The section custom is invalid (the error's cause names the invalid setting and the reason, not the value), the config has a section of an earlier version, or the service info isn't of type drs.

ValidationError

A section of FOCA is invalid, e.g., the service info.

RuntimeError

No service info is configured (e.g., an overlay sets service_info: null).

main

main() -> None

Run the app with Flask's development server, on the configured port.

For development only; not for production.

gunicorn_config

Gunicorn settings of the image (production WSGI server).

The image runs gunicorn --config python:drs_filer.gunicorn_config 'drs_filer.app:create_app()'. Override the settings via GUNICORN_CMD_ARGS (e.g., --workers 2 --threads 8), which takes precedence over this module (cf. https://docs.gunicorn.org/en/stable/settings.html).

The app is not preloaded (no preload_app): each worker creates it after forking, as MongoDB clients must not be shared across forks.

Forwarded headers (X-Forwarded-*) are trusted from Gunicorn's default (127.0.0.1, or FORWARDED_ALLOW_IPS) only, not from any client; behind a proxy that sets them, set FORWARDED_ALLOW_IPS to its addresses.

Configuration

custom_config

Models of the app's own configuration (custom section of the config).

FOCA validates the section against CustomConfig on startup (cf. drs_filer.app.create_app()), so that invalid settings fail the start instead of requests. The service info is configured in FOCA's section service_info, not here.

DrsConfig

Bases: FOCABaseConfig

Model for the DRS host of the app.

The self_uri of each object is the hostname-based DRS URI of the host, drs://<hostname>/<id> (with the identifier percent-encoded), computed when the object is served. DRS clients resolve it to https://<hostname>/ga4gh/drs/v1/objects/<id>, always on port 443.

Parameters:

Name Type Description Default
hostname

Public host name of the app, without scheme, port or path; required.

required

Attributes:

Name Type Description
hostname str

Public host name of the app.

Raises:

Type Description
ValidationError

The host name is missing, or is not a host name.

Example

DrsConfig(hostname="drs.example.org").hostname 'drs.example.org'

check_hostname classmethod

check_hostname(value: str) -> str

Check that the host name is a host name only.

Parameters:

Name Type Description Default
value str

Host name.

required

Returns:

Type Description
str

The host name.

Raises:

Type Description
ValueError

The host name is empty, has a scheme, port, path, uppercase letters or other characters (e.g., an IPv6 address, which DRS URIs can't have), is a number (e.g., a port), or an invalid IPv4 address.

IdConfig

Bases: IdConfig

Model for generating identifiers of objects or access methods.

FOCA's model (foca.models.config.IdConfig), for FOCA's generate_id(), narrowed: FOCA's checks of the character set apply (not empty, no /, not dots only, no expression it recognizes), and only the unreserved characters of URLs are allowed, which are also the default, as identifiers are part of URLs (e.g., self_uri); this also refuses expressions that FOCA doesn't recognize. The length is an integer, also in a string (e.g., from an environment variable), but not a boolean.

Parameters:

Name Type Description Default
charset

The allowed characters (duplicates are ignored); not an expression (e.g., string.ascii_letters + string.digits), which earlier versions evaluated.

required
length

Length of generated identifiers.

required

Attributes:

Name Type Description
charset str

The allowed characters.

length PositiveInteger

Length of generated identifiers.

Raises:

Type Description
ValidationError

The character set is empty, consists of dots only, or has characters other than letters, digits and -._~, or the length is not a positive integer.

Example

IdConfig(charset="abc123", length=8) IdConfig(charset='abc123', length=8)

check_unreserved classmethod

check_unreserved(value: str) -> str

Check that the character set has unreserved characters of URLs only.

Parameters:

Name Type Description Default
value str

Character set.

required

Returns:

Type Description
str

The character set.

Raises:

Type Description
ValueError

The character set has other characters, e.g., as an expression.

ListConfig

Bases: FOCABaseConfig

Model for the pages of the object list (GET /objects).

Parameters:

Name Type Description Default
default_page_size

Number of objects of a page if the request has no pageSize; at most max_page_size.

required
max_page_size

Largest number of objects of a page, at most MAX_PAGE_SIZE; larger pageSizes are reduced to it.

required

Attributes:

Name Type Description
default_page_size PositiveInteger

Number of objects of a page if the request has no pageSize.

max_page_size Annotated[PositiveInteger, Field(le=MAX_PAGE_SIZE)]

Largest number of objects of a page.

Raises:

Type Description
ValidationError

A setting is not a positive integer, the maximum is larger than MAX_PAGE_SIZE, or the default page size is larger than the maximum.

Example

ListConfig(default_page_size="10").default_page_size 10

check_default_page_size

check_default_page_size() -> ListConfig

Refuse a default page size larger than the maximum.

Returns:

Type Description
ListConfig

The settings.

Raises:

Type Description
ValueError

The default page size is larger than the maximum.

ObjectsConfig

Bases: FOCABaseConfig

Model for the settings of objects.

Parameters:

Name Type Description Default
id

Generated identifiers of objects.

required
list

Pages of the object list (GET /objects).

required

Attributes:

Name Type Description
id IdConfig

Generated identifiers of objects.

list ListConfig

Pages of the object list.

AccessMethodsConfig

Bases: FOCABaseConfig

Model for the settings of access methods.

Parameters:

Name Type Description Default
id

Generated identifiers of access methods.

required

Attributes:

Name Type Description
id IdConfig

Generated identifiers of access methods.

StatsConfig

Bases: FOCABaseConfig

Model for the stats of the objects in the service info.

GET /service-info serves drs.objectCount and drs.totalObjectSize (DRS 1.5.0), computed from the database and kept for cache_seconds in each app process (each Gunicorn worker), so that frequent requests to the public endpoint don't read all objects each time. Writes through the same process recompute them at once; other processes serve them up to cache_seconds late.

Parameters:

Name Type Description Default
enabled

Whether the service info has the stats; False leaves them out (they are optional), e.g., where reads require login and the number of objects shouldn't show either.

required
cache_seconds

How long the stats are kept, in seconds; 0 computes them for each request.

required

Attributes:

Name Type Description
enabled bool

Whether the service info has the stats.

cache_seconds NonNegativeInteger

How long the stats are kept, in seconds.

Raises:

Type Description
ValidationError

A setting is invalid.

Example

StatsConfig(cache_seconds="0").cache_seconds 0

BulkConfig

Bases: FOCABaseConfig

Model for bulk requests.

The authorization info of several objects (OPTIONS /objects) takes at most max_request_length identifiers; requests with more get 413. The maximum is served in the service info (maxBulkRequestLength of DRS 1.5.0).

Parameters:

Name Type Description Default
max_request_length

Maximum number of identifiers of a bulk request, counted as sent (duplicates too).

required

Attributes:

Name Type Description
max_request_length PositiveInteger

Maximum number of identifiers of a bulk request.

Raises:

Type Description
ValidationError

The maximum is not a positive integer.

Example

BulkConfig(max_request_length="50").max_request_length 50

CustomConfig

Bases: FOCABaseConfig

Model for the app's own configuration (custom).

Unknown keys are refused, e.g., misspelled ones, the service info, which is configured in FOCA's section service_info, and the public URL of earlier versions (service), with a hint to its replacement.

Parameters:

Name Type Description Default
drs

DRS host of the app; required.

required
objects

Settings of objects.

required
access_methods

Settings of access methods.

required
stats

Stats of the objects in the service info.

required
bulk

Bulk requests.

required

Attributes:

Name Type Description
drs DrsConfig

DRS host of the app.

objects ObjectsConfig

Settings of objects.

access_methods AccessMethodsConfig

Settings of access methods.

stats StatsConfig

Stats of the objects in the service info.

bulk BulkConfig

Bulk requests.

Raises:

Type Description
ValidationError

A setting is missing, invalid or unknown.

check_removed classmethod

check_removed(data: Any) -> Any

Refuse the public URL of earlier versions, naming its replacement.

Parameters:

Name Type Description Default
data Any

Settings.

required

Returns:

Type Description
Any

The settings.

Raises:

Type Description
ValueError

The settings have the section service.

utils

Typed access to the configuration and collections of the app.

get_foca_config

get_foca_config() -> Config

Get the FOCA configuration of the current app.

Returns:

Type Description
Config

FOCA configuration.

get_custom_config

get_custom_config() -> CustomConfig

Get the app's own configuration (custom) of the current app.

FOCA validates the section against CustomConfig on startup and keeps it as an untyped extra field of its configuration.

Returns:

Type Description
CustomConfig

The custom configuration.

Raises:

Type Description
RuntimeError

The app has no custom configuration of type CustomConfig (e.g., it was not created by create_app()).

get_collection

get_collection(name: str) -> Collection[dict[str, Any]]

Get a collection of the app's database.

Parameters:

Name Type Description Default
name str

Name of the collection, as configured.

required

Returns:

Type Description
Collection[dict[str, Any]]

MongoDB collection.

Raises:

Type Description
KeyError

The collection isn't configured, or FOCA hasn't registered it (no database configured, or no client).

Controllers

server

Controllers for DRS endpoints.

self_uri

self_uri(object_id: str) -> str

Get the self_uri of an object: its DRS URI on the configured host.

A hostname-based DRS URI, drs://<hostname>/<id>, of the host name of the config (custom.drs.hostname, not of the request, whose Host clients set), with the identifier percent-encoded, as DRS requires (the unreserved characters of URLs stay as they are, except in the identifiers . and .., which would be dot segments that clients remove when resolving the URI, RFC 3986, section 5.2.4).

Parameters:

Name Type Description Default
object_id str

Identifier of the object.

required

Returns:

Type Description
str

The DRS URI of the object.

Example

With custom.drs.hostname: drs.example.org, self_uri("a:b") is drs://drs.example.org/a%3Ab.

ListDrsObjects

ListDrsObjects(pageSize: int | None = None, pageToken: str | None = None) -> dict[str, Any]

Get a page of the DRS objects.

Objects are listed by their database identifier (_id), descending, and served as the object reads serve them (_read()). _ids are unique, so no object is skipped or listed twice; they start with the time of registration (in seconds), so the list is newest first, to the second (in the same second, and across the app instances and the database server, which generates the _ids of objects created by PUT, with clock skew, the order is arbitrary, but fixed). Objects whose _id isn't an ObjectId (not stored by DRS-Filer) aren't listed. Replacing an object (PUT) keeps its _id, so its place in the list. The page token is the _id of the last object of the previous page, as 24 hexadecimal digits (PAGE_TOKEN). Connexion checks it against the pattern of the specification (FOCA anchors $ at the very end, so a trailing newline doesn't match), unless a patch of the specification drops the pattern, so it is checked again here.

Parameters:

Name Type Description Default
pageSize int | None

Maximum number of objects of the page; by default custom.objects.list.default_page_size, and at most max_page_size, to which larger values are reduced.

None
pageToken str | None

nextPageToken of the previous page.

None

Returns:

Type Description
dict[str, Any]

The page (DrsObjectPage): its objects, and nextPageToken unless it

dict[str, Any]

is the last page.

Raises:

Type Description
InvalidFieldsProblem

The page token is malformed; the problem details don't quote it.

GetObject

GetObject(object_id: str, expand: bool = False) -> dict[str, Any]

Get DRS object.

As the object reads serve it (_read()).

Parameters:

Name Type Description Default
object_id str

Identifier of DRS object to be retrieved.

required
expand bool

Whether to expand nested bundles; ignored, as bundles are served as registered.

False

Returns:

Type Description
dict[str, Any]

DRS object as dictionary, JSONified if returned in app context.

GetAccessURL

GetAccessURL(object_id: str, access_id: str) -> dict[str, Any]

Get access URL of DRS object.

Parameters:

Name Type Description Default
object_id str

Identifier of DRS object to be retrieved.

required
access_id str

Identifier of method giving access to DRS object.

required

Returns:

Type Description
dict[str, Any]

Object with access information for DRS object, containing a URL and

dict[str, Any]

any relevant header information; response is JSONified if returned in

dict[str, Any]

app context.

GetServiceInfo

GetServiceInfo() -> dict[str, Any]

Show information about this service.

Returns:

Type Description
dict[str, Any]

Service info: the stored one, with the DRS fields that the app

dict[str, Any]

computes (drs_service_fields()).

PostServiceInfo

PostServiceInfo() -> tuple[None, int, dict[str, Any]]

Set information about this service.

Returns:

Type Description
tuple[None, int, dict[str, Any]]

An empty 201 response with headers.

DeleteObject

DeleteObject(object_id: str) -> str

Delete DRS object.

Parameters:

Name Type Description Default
object_id str

Identifier of DRS object to be deleted.

required

Returns:

Type Description
str

object_id of deleted object.

DeleteAccessMethod

DeleteAccessMethod(object_id: str, access_id: str) -> str

Delete DRS object's Access Method.

Parameters:

Name Type Description Default
object_id str

Identifier of DRS object to be deleted.

required
access_id str

Identifier of the access method to be deleted

required

Returns:

Type Description
str

access_id of deleted object.

Raises:

Type Description
ObjectNotFound

If the object doesn't exist.

AccessMethodNotFound

If the object has no access method with the given identifier (also if it has no access methods, e.g., a bundle).

AccessMethodNotDeleted

If attempting to delete the last remaining access method, i.e., if the object has no access method with another identifier.

InternalServerError

If the access method could be deleted, but wasn't.

RegisterObject

RegisterObject() -> str

Register new DRS object.

Returns:

Type Description
str

Identifier of the registered object, generated by the app.

PostObject

PostObject(**kwargs: Any) -> NoReturn

Get a DRS object with passports: not implemented.

Parameters:

Name Type Description Default
**kwargs Any

Parameters and request body of the operation; ignored.

{}

Raises:

Type Description
PassportOperationNotImplemented

Always.

PostAccessURL

PostAccessURL(**kwargs: Any) -> NoReturn

Get the access URL of a DRS object with passports: not implemented.

Parameters:

Name Type Description Default
**kwargs Any

Parameters and request body of the operation; ignored.

{}

Raises:

Type Description
PassportOperationNotImplemented

Always.

GetBulkObjects

GetBulkObjects(**kwargs: Any) -> NoReturn

Get several DRS objects, with passports: not implemented.

Parameters:

Name Type Description Default
**kwargs Any

Parameters and request body of the operation; ignored.

{}

Raises:

Type Description
PassportOperationNotImplemented

Always.

GetBulkAccessURL

GetBulkAccessURL(**kwargs: Any) -> NoReturn

Get the access URLs of several DRS objects, with passports: not implemented.

Parameters:

Name Type Description Default
**kwargs Any

Parameters and request body of the operation; ignored.

{}

Raises:

Type Description
PassportOperationNotImplemented

Always.

OptionsObject

OptionsObject(object_id: str) -> dict[str, Any]

Get the authorization info of a DRS object.

How to authorize GetObject (cf. drs_filer.ga4gh.drs.authorizations.object_authorizations()).

Parameters:

Name Type Description Default
object_id str

Identifier of the DRS object.

required

Returns:

Type Description
dict[str, Any]

Authorizations of the object, JSONified if returned in app context.

OptionsBulkObject

OptionsBulkObject() -> dict[str, Any]

Get the authorization info of several DRS objects.

How to authorize GetObject for each (cf. drs_filer.ga4gh.drs.authorizations.bulk_object_authorizations()).

Returns:

Type Description
dict[str, Any]

Summary, unresolved identifiers and Authorizations of the

dict[str, Any]

resolved objects, JSONified if returned in app context.

PutObject

PutObject(object_id: str) -> str

Add/replace DRS object with a user-supplied ID.

Parameters:

Name Type Description Default
object_id str

Identifier of DRS object to be created/updated.

required

Returns:

Type Description
str

Identifier of created/updated DRS object.

register_objects

Controller for registering new DRS objects.

register_object

register_object(data: dict[str, Any], object_id: str | None = None, retries: int = 9) -> str

Register data object.

The object is stored without self_uri, which is computed when it is served (cf. drs_filer.ga4gh.drs.server.self_uri()).

Parameters:

Name Type Description Default
data dict[str, Any]

Request object of type DrsObjectRegister.

required
object_id str | None

DRS object identifier. Auto-generated if not provided.

None
retries int

If object_id is not supplied, how many times should the generation of a random identifier and insertion into the database be retried in case of DuplicateKeyErrors.

9

Returns:

Type Description
str

A unique identifier for the object.

service_info

Controller for service info endpoint.

The service info is stored as a single record, with _id CURRENT_ID, which GET /service-info serves, with the DRS fields that the app computes (drs_service_fields(), with the stats of the objects of object_stats()). On startup, the service info of the config (FOCA's section service_info, with the version of the package unless service_info.service.version is set) replaces it, if it differs; POST /service-info replaces it until the next startup. Both remove the records that earlier versions stored (one per service info id).

RegisterServiceInfo

RegisterServiceInfo()

Tool class for registering service info.

Sets the service info from the config on startup, and from requests.

Initialize class requirements.

Attributes:

Name Type Description
db_coll_info

Database collection storing service info objects.

get_service_info

get_service_info() -> dict[str, Any]

Get the current service info from the database.

Returns:

Type Description
dict[str, Any]

Current service info details.

Raises:

Type Description
NotFound

No service info is set.

set_service_info_from_config

set_service_info_from_config() -> None

Create or update service info from service configuration.

Will create service info if it does not exist or current configuration differs from available one, replacing service info set by a request (POST /service-info). FOCA validates the service info of the config on startup, against the service info specification.

Raises:

Type Description
RuntimeError

No service info is configured (service_info).

set_service_info_from_app_context

set_service_info_from_app_context(data: dict[str, Any]) -> dict[str, Any]

Set service info from a request.

Parameters:

Name Type Description Default
data dict[str, Any]

Service info according to API specification.

required

Returns:

Type Description
dict[str, Any]

Response headers.

object_stats

object_stats() -> dict[str, int]

Get the stats of the registered objects.

They are kept in the app (current_app.extensions[STATS_CACHE], so per process) for custom.stats.cache_seconds, as computing them reads each object; writes of the process make them stale (invalidate_object_stats()). Stats computed while a write of another thread of the process (Gunicorn's threads) made them stale aren't kept, as they may miss that write.

Only one thread of the process computes them at a time; threads that need them meanwhile wait, and get the stats it keeps. They are kept from the time they were computed, so that slow computations are kept too.

Returns:

Type Description
dict[str, int]

The stats of DrsService (DRS 1.5.0), see _compute_object_stats().

invalidate_object_stats

invalidate_object_stats() -> None

Make the kept stats of the objects stale, after writes of objects.

The next request of the service info computes them again, and stats being computed meanwhile aren't kept. Other processes keep theirs until they expire.

invalidates_object_stats

invalidates_object_stats(func: Callable[P, R]) -> Callable[P, R]

Decorate the controllers that write objects.

The kept stats are made stale after the write, also if it fails, as it may have changed objects before failing.

Parameters:

Name Type Description Default
func Callable[P, R]

Controller.

required

Returns:

Type Description
Callable[P, R]

The controller, which makes the kept stats stale after each call.

drs_service_fields

drs_service_fields() -> dict[str, Any]

Get the DRS fields of the service info, which the app computes.

They are added to the stored service info when it is served (GET /service-info), not stored, and can't be posted.

Returns:

Type Description
dict[str, Any]

The fields of DrsService (DRS 1.5.0): maxBulkRequestLength

dict[str, Any]

(deprecated) and drs, with the bulk maximum

dict[str, Any]

(custom.bulk.max_request_length) and, unless

dict[str, Any]

custom.stats.enabled is false, the stats of the objects

dict[str, Any]

(object_stats()).

Errors

exceptions

Exceptions of the app and their problem details (RFC 9457).

The classes are FOCA's framework-neutral ones (foca.errors), which replace those of Werkzeug and Connexion before FOCA's release on ASGI.

AccessMethodNotDeleted

Bases: Conflict

Raised when deleting the last remaining access method of an object.

AccessMethodNotFound

Bases: NotFound

Raised when an access method of an object was not found.

The object and access method are those of the given identifiers.

ObjectNotFound

Bases: NotFound

Raised when object with given object identifier was not found.

URLNotFound

Bases: NotFound

Raised when Access URL for object was not found.

ValidationError

Bases: Exception

Value or object is not compatible with required type or schema.

OperationNotImplemented

Bases: HTTPError, NotImplemented

Raised for operations of the DRS specification that aren't implemented.

PassportOperationNotImplemented

Bases: OperationNotImplemented

Raised for the passport POST operations of the DRS specification.

DRS-Filer doesn't implement them, by design (see "Passport POST endpoints" in docs/api.md).

BulkObjectIdsMissing

Bases: BadRequest

Raised for bulk requests without identifiers (bulk_object_ids).

BulkRequestTooLarge

Bases: PayloadTooLarge

Raised for bulk requests with more identifiers than allowed.

The maximum is custom.bulk.max_request_length of the config, served as maxBulkRequestLength in the service info.