Skip to content

API reference

The blocking service classes, their async twins in water_ogcapi.aio, and the types both return.

Services

Bases: OGCService

Blocking client for the USGS Water Data OGC API, as water_ogcapi.aio.NWIS.

Parameters:

Name Type Description Default
api_key str

A USGS API key, as for water_ogcapi.aio.NWIS.

None
transport Transport

Sends every request, as for OGCService.

None

Raises:

Type Description
ValidationError

If the key holds a character other than printable ASCII.

Bases: OGCService

Blocking client for the USGS FabricData service, as water_ogcapi.aio.FabricData.

Parameters:

Name Type Description Default
transport Transport

Sends every request, as for OGCService.

None

Bases: OGCService

Blocking client for the GeoConnex reference features, as water_ogcapi.aio.GeoConnex.

Parameters:

Name Type Description Default
transport Transport

Sends every request, as for OGCService.

None

Blocking client for one OGC API Features service.

Runs a water_ogcapi.aio.OGCService of its own on the background loop. Its methods collections, queryables, schema, iter_pages, collect, and item block on the async methods of the same name. A Transport passed here binds to that loop, so share it only among sync services (D-10); close() closes it, and a service sharing it reconnects on its next request.

Parameters:

Name Type Description Default
base_url str

The service's landing page, as for water_ogcapi.aio.OGCService.

required
transport Transport

Sends every request, as for water_ogcapi.aio.OGCService.

None

base_url property

The landing page URL, without a trailing slash.

collections()

Return the collection index from /collections.

The index is cached for an hour, then revalidated (D-07); refresh drops it.

Raises:

Type Description
ServiceError

If the request fails or the body is not a JSON object with a collections list. Nothing is cached, so the next call asks again.

ValueError

If an entry of collections is not an object with a string id.

queryables(collection)

Return the properties a query on collection can filter on.

The document is cached for an hour, then revalidated (D-07); refresh drops it.

Parameters:

Name Type Description Default
collection str

The collection id.

required

Raises:

Type Description
ServiceError

If the request fails, with status 404 for an unknown collection, or the body is not a JSON object with a properties object.

ValidationError

Before any request, if collection is empty, ., or ...

schema(collection)

Return the properties each feature of collection carries.

The document is cached for an hour, then revalidated (D-07); refresh drops it.

Parameters:

Name Type Description Default
collection str

The collection id.

required

Raises:

Type Description
ServiceError

If the request fails, with status 404 for an unknown collection, or the body is not a JSON object with a properties object.

ValidationError

Before any request, if collection is empty, ., or ...

iter_pages(collection, *, params=None, bbox=None, geometry=None, filter=None, ids=None, id_property=None, split_datetime=None, sites_per_piece=None, validate=True, resume=None)

Yield each page of a collection's items, following next links (D-34).

Only a page without a next link ends the traversal. A page shorter than requested, or one without numberMatched, ends nothing. A split query runs its pieces concurrently and yields pages as they arrive (D-56).

Parameters:

Name Type Description Default
collection str

The collection id.

required
params mapping of str to str

Query parameters of the first request, such as limit or datetime, with f=json and the profile's default_limit added unless given. Later requests take their query from the next link.

None
bbox sequence of float

(west, south, east, north) in CRS84, or six values with the minimum and maximum heights, sent as the bbox parameter with every digit kept. West above east crosses the antimeridian.

None
geometry mapping or GeoInterface

A GeoJSON geometry, or an object with __geo_interface__ such as a shapely polygon, in CRS84. Its bbox is sent in place of the geometry (D-11), so the result holds every feature intersecting that bbox; exact containment is the caller's post-filter.

None
filter str or mapping

A CQL2 filter, spatial predicates such as s_intersects included. A str is CQL2-Text, sent as the filter parameter of a GET. A mapping is CQL2-JSON, sent as the body of a POST with Content-Type: application/query-cql-json; every next link gets the same body, since a GET there drops the filter (D-38).

None
ids sequence of str or int

Values of id_property to match, sent as the CQL2-JSON filter {"op": "in", "args": [{"property": id_property}, ids]}, as filter sends a mapping. Each value goes out with its type, so "01646500" keeps its leading zero.

None
id_property str

The property ids matches, such as id for feature ids or monitoring_location_id for the sites of an NWIS time series.

None
split_datetime ('year', 'month')

NWIS only (D-35, D-56): split the datetime interval in params at calendar boundaries in UTC into pieces that run concurrently, up to the transport's max_concurrent at once, each following its own next links. The interval needs both ends, as dates or timestamps with an offset, and each piece ends one microsecond before the next begins. Every piece costs at least one request, so size pieces near one page.

'year'
sites_per_piece int

NWIS only (D-35, D-56): split the site list, ids or a comma-separated monitoring_location_id in params, into lists of this many sites that run concurrently as split_datetime pieces do. A site listed twice is sent once. Not with split_datetime.

None
validate bool

Before the first page request, check collection against the collection index, and each name in params outside QUERY_PARAMS, and id_property, against the collection's queryables, from metadata cached for an hour (D-07). pygeoapi drops a name it does not know, so an unchecked typo returns the whole collection. Defaults to True; False skips the check, for a server that accepts a name its queryables leave out.

True
resume Checkpoint

Continue a query from a Checkpoint: a page's checkpoint or a PaginationError's (D-52). Its pending requests are sent as stored, so no query keyword may come with it, validate is ignored, and no request it holds is sent again.

None

Yields:

Type Description
Page

One per response, the decoded document in body and its bytes in content. Its checkpoint is where the query stands once the caller holds it.

Raises:

Type Description
ValidationError

Before any request, when collection is empty, ., or .., both bbox and geometry, or ids and filter, are given, ids is a str or bytes, empty, or lacks id_property, bbox or geometry is malformed, a CQL2-JSON filter holds a NaN or infinite number, a filter is empty, params also holds a parameter a keyword sets (bbox, filter, filter-lang) or a credential such as api_key, or limit is not an integer from 1 to the profile's max_limit, or a split is given to a service other than NWIS, both splits are given, or the query has no closed datetime interval or site list to split. With validate, before the first page request, when the collection, a name in params, or id_property is unknown; the message lists the valid ones. With resume, when a query keyword comes with it or it is a checkpoint of another service or collection.

TypeError

Before any request, when a CQL2-JSON filter holds a value JSON cannot encode, such as a set.

ServiceError

With validate, when a metadata request fails.

PaginationError

When a request fails, a body is not a FeatureCollection with well-formed links, or a next link repeats a request already answered, leaves the scheme, host, and port of base_url, or a page has a link that carries a credential (D-53). It is raised once every page that arrived has been yielded; its failures name each such request or link by URL, and its checkpoint is where the query stands.

collect(collection, *, params=None, bbox=None, geometry=None, filter=None, ids=None, id_property=None, split_datetime=None, sites_per_piece=None, validate=True, keep_pages=False, resume=None)

Fetch every page of a collection's items into one QueryResult (D-22).

Parameters:

Name Type Description Default
collection str

The collection id.

required
params Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
bbox Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
geometry Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
filter Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
ids Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
id_property Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
split_datetime Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
sites_per_piece Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
validate bool

Check the query against cached metadata first, as for iter_pages.

True
keep_pages bool

Keep each page's response bytes in Page.content (D-23). Page bodies are always dropped. With resume, it applies to the new pages; held pages keep what the earlier call kept.

False
resume QueryResult or Checkpoint

Continue a query that stopped on a failure (D-52): the result of a PartialResultsError, or the checkpoint of a PaginationError raised before any page arrived. The result's pages and features come first in the new result, and no request for them is sent. No query keyword may come with it.

None

Returns:

Type Description
QueryResult

geojson holds the features of all pages in the order they arrived, those of resume first.

Raises:

Type Description
ValidationError

On a malformed query or, with validate, an unknown name, as for iter_pages. With resume, before any request, when a query keyword comes with it, it is from another service or collection, a QueryResult has no checkpoint, or a Checkpoint holds pages, which only the QueryResult that holds them can carry.

TypeError

Before any request, when a CQL2-JSON filter holds a value JSON cannot encode, as for iter_pages.

ServiceError

With validate, when a metadata request fails.

PartialResultsError

When a page fails after at least one succeeded, resume's included. Its result holds the pages that succeeded and the checkpoint to resume.

PaginationError

When no page arrives, as when the first page of an unsplit query fails.

item(collection, item_id, *, params=None, validate=True)

Fetch one feature of a collection by its id (D-22).

Parameters:

Name Type Description Default
collection str

The collection id.

required
item_id str or int

The feature id, percent-encoded into the URL path.

required
params mapping of str to str

Query parameters, such as crs or skipGeometry, with f=json added unless given.

None
validate bool

Before the request, check collection against the cached collection index, as iter_pages does. Defaults to True.

True

Returns:

Type Description
Page

body holds the decoded Feature and content its bytes. feature_count is 1, and number_matched and number_returned are None.

Raises:

Type Description
ServiceError

If the request fails, with status 404 for an unknown id, or the body is not a Feature whose links member, when present, is a list. With validate, also when the metadata request fails.

ValidationError

Before any request, if collection or item_id is empty, ., or .., which would address another path, or params carries a credential such as api_key. With validate, if the collection is unknown.

refresh()

Drop every cached metadata document, so the next call fetches it again.

close()

Close the transport, whether this service created it or it was passed.

What one service accepts and sends, read by its service class (D-13, D-41).

Parameters:

Name Type Description Default
base_url str

The landing page.

required
default_limit int

The limit an items query sends when its params hold none.

required
max_limit int

The largest limit the service accepts.

required
key_env str or None

The environment variable that holds the service's API key, sent in the X-Api-Key header (D-18). None, the default, for a service sent no key.

None
rate_limit_window float or None

Seconds over which the service's X-RateLimit-Limit counts, read by its Governor (D-49). None, the default, for a service that sends no X-RateLimit-* headers.

None

Bounded, retrying async HTTP client.

The client and its semaphore are created on the first request, so construction performs no I/O. Both then belong to that event loop for the life of the instance: a later request from a different loop raises rather than failing later under contention. Use one transport per loop, or aclose() between loops. Retries cover transport errors and the status codes in RETRY_STATUS.

Parameters:

Name Type Description Default
timeout float

Seconds each attempt may take, from sending the request to reading the last body byte, defaults to 30. httpx2 also applies it to each connect, read, write, and pool wait. A timed-out attempt is retried. Waiting for a concurrency permit is not bounded.

30.0
max_concurrent int

Requests in flight at once, defaults to 4. An explicit semaphore, not a connection-pool limit: over HTTP/2 a single connection multiplexes many streams, so pool size does not bound concurrency. Held only while a request is in flight, never across a backoff wait.

4
max_retries int

Retries after the first attempt, defaults to 3.

3
backoff float

Base of the exponential backoff in seconds, defaults to 0.5.

0.5
http2 bool

Negotiate HTTP/2, defaults to True.

True
transport AsyncBaseTransport

Injected transport, for tests.

None

Raises:

Type Description
ValidationError

If max_concurrent is below 1, or max_retries or backoff is negative. A zero-permit semaphore would block every request forever.

timeout property

Seconds each attempt may take.

max_concurrent property

Requests in flight at once.

max_retries property

Retries after the first attempt.

backoff property

Base of the exponential backoff in seconds.

http2 property

Whether HTTP/2 is negotiated.

get(url, *, params=None, headers=None, governor=None) async

Send a GET through request, which documents the parameters and errors.

request(method, url, *, params=None, headers=None, content=None, governor=None) async

Send a request, retrying transient failures.

A POST is retried like a GET: this package posts only queries, which change nothing on the server (docs/design.md D-38).

Parameters:

Name Type Description Default
method str

HTTP method, such as GET or POST.

required
url str

Absolute URL to fetch.

required
params mapping of str to str

Query parameters, merged into any query already in url. A name in both takes its value from params. Credentials are not allowed here.

None
headers mapping of str to str

Request headers, credentials included. Each value must be printable ASCII.

None
content bytes

Request body, sent unchanged on every attempt.

None
governor Governor

Paces every attempt, retries included, and reads the rate-limit headers of every response (D-06). Each service class passes its own.

None

Returns:

Type Description
Response

The first 2xx response. A 304 is returned, not raised, so conditional revalidation works.

Raises:

Type Description
RateLimitError

On a final 429, or on a 429 whose Retry-After exceeds MAX_SLEEP. Carries the parsed wait, the remaining count, and the attempt count. Every error carries the method and body of the request (D-38).

ServiceError

On any other status of 400 or above, on a redirect, on a malformed URL or undecodable body, when retries are exhausted, or when aclose() ran while the call waited for a permit or a backoff.

RuntimeError

If called from an event loop other than the one this transport bound to.

ValidationError

If params carries a credential such as api_key, or a header value is not printable ASCII. The message names the header, never its value.

aclose() async

Close the underlying client and release the loop binding.

Call this from the loop that used the transport, before that loop exits. Closing pooled connections from a different loop is what fails, and the binding is released either way so a failed close cannot strand the instance.

Spaces the starts of one service's requests so its quota lasts (D-06).

Transport.request calls wait before each attempt and observe on each response, retries included. Each X-RateLimit-Limit value keeps its own reading, since a default NWIS key counts /items and metadata separately, and the widest interval of the readings from the last window seconds applies; with none, the static interval does. With remaining of limit left, the interval is window / remaining - 8 * window / limit seconds, from 0 at an eighth of the quota to at most 60.

Parameters:

Name Type Description Default
window float or None

Seconds over which the service's X-RateLimit-Limit counts. None ignores rate-limit headers, for a service that sends none.

required
interval float

Seconds between request starts while no reading from the last window seconds applies, defaults to 1. The first request never waits.

STATIC_INTERVAL

Raises:

Type Description
ValidationError

If window is not positive or interval is negative.

window property

Seconds over which the service's X-RateLimit-Limit counts.

interval property

Seconds between request starts while no recent reading applies.

wait() async

Wait until the request may start: one interval after the previous start.

A reading or a 429 that arrives during the wait applies to it, and a cancelled wait books nothing.

observe(status, headers)

Read the counts on one response, and a 429's Retry-After.

A response a CDN served, or one without both counts, leaves the readings as they were. A 429's Retry-After holds back every later start for that long, up to 60 seconds.

Parameters:

Name Type Description Default
status int

HTTP status code.

required
headers mapping of str to str

Response headers with lowercase keys.

required

Async API

The async service classes, for code that runs its own event loop (D-48).

Each class has the name and constructor of its blocking twin in water_ogcapi, and each method is a coroutine, apart from iter_pages, which returns an async iterator. A Transport binds to the event loop of its first request (D-10).

import asyncio

from water_ogcapi.aio import NWIS


async def main() -> None:
    async with NWIS() as nwis:
        result = await nwis.collect("daily", params={"monitoring_location_id": "USGS-01646500"})


asyncio.run(main())

OGCService

Async client for one OGC API Features service.

Construction performs no HTTP (docs/design.md D-10). The first request binds the transport to the running event loop.

Parameters:

Name Type Description Default
base_url str

The service's landing page, such as https://api.waterdata.usgs.gov/ogcapi/v1. A trailing slash is ignored. Defaults to the profile's base_url; required where profile is None.

None
transport Transport

Sends every request. The service closes a transport it created and leaves a passed one open, so several services can share one.

None

Attributes:

Name Type Description
profile ServiceProfile or None

The service's page sizes, key convention, and rate-limit window, set by each service class. None here: a query sends the server's default limit, any limit goes unchecked, and requests start 1 s apart (D-49).

base_url property

The landing page URL, without a trailing slash.

collections() async

Return the collection index from /collections.

The index is cached for an hour, then revalidated (D-07); refresh drops it.

Raises:

Type Description
ServiceError

If the request fails or the body is not a JSON object with a collections list. Nothing is cached, so the next call asks again.

ValueError

If an entry of collections is not an object with a string id.

queryables(collection) async

Return the properties a query on collection can filter on.

The document is cached for an hour, then revalidated (D-07); refresh drops it.

Parameters:

Name Type Description Default
collection str

The collection id.

required

Raises:

Type Description
ServiceError

If the request fails, with status 404 for an unknown collection, or the body is not a JSON object with a properties object.

ValidationError

Before any request, if collection is empty, ., or ...

schema(collection) async

Return the properties each feature of collection carries.

The document is cached for an hour, then revalidated (D-07); refresh drops it.

Parameters:

Name Type Description Default
collection str

The collection id.

required

Raises:

Type Description
ServiceError

If the request fails, with status 404 for an unknown collection, or the body is not a JSON object with a properties object.

ValidationError

Before any request, if collection is empty, ., or ...

refresh()

Drop every cached metadata document, so the next call fetches it again.

iter_pages(collection, *, params=None, bbox=None, geometry=None, filter=None, ids=None, id_property=None, split_datetime=None, sites_per_piece=None, validate=True, resume=None) async

Yield each page of a collection's items, following next links (D-34).

Only a page without a next link ends the traversal. A page shorter than requested, or one without numberMatched, ends nothing. A split query runs its pieces concurrently and yields pages as they arrive (D-56).

Parameters:

Name Type Description Default
collection str

The collection id.

required
params mapping of str to str

Query parameters of the first request, such as limit or datetime, with f=json and the profile's default_limit added unless given. Later requests take their query from the next link.

None
bbox sequence of float

(west, south, east, north) in CRS84, or six values with the minimum and maximum heights, sent as the bbox parameter with every digit kept. West above east crosses the antimeridian.

None
geometry mapping or GeoInterface

A GeoJSON geometry, or an object with __geo_interface__ such as a shapely polygon, in CRS84. Its bbox is sent in place of the geometry (D-11), so the result holds every feature intersecting that bbox; exact containment is the caller's post-filter.

None
filter str or mapping

A CQL2 filter, spatial predicates such as s_intersects included. A str is CQL2-Text, sent as the filter parameter of a GET. A mapping is CQL2-JSON, sent as the body of a POST with Content-Type: application/query-cql-json; every next link gets the same body, since a GET there drops the filter (D-38).

None
ids sequence of str or int

Values of id_property to match, sent as the CQL2-JSON filter {"op": "in", "args": [{"property": id_property}, ids]}, as filter sends a mapping. Each value goes out with its type, so "01646500" keeps its leading zero.

None
id_property str

The property ids matches, such as id for feature ids or monitoring_location_id for the sites of an NWIS time series.

None
split_datetime ('year', 'month')

NWIS only (D-35, D-56): split the datetime interval in params at calendar boundaries in UTC into pieces that run concurrently, up to the transport's max_concurrent at once, each following its own next links. The interval needs both ends, as dates or timestamps with an offset, and each piece ends one microsecond before the next begins. Every piece costs at least one request, so size pieces near one page.

'year'
sites_per_piece int

NWIS only (D-35, D-56): split the site list, ids or a comma-separated monitoring_location_id in params, into lists of this many sites that run concurrently as split_datetime pieces do. A site listed twice is sent once. Not with split_datetime.

None
validate bool

Before the first page request, check collection against the collection index, and each name in params outside QUERY_PARAMS, and id_property, against the collection's queryables, from metadata cached for an hour (D-07). pygeoapi drops a name it does not know, so an unchecked typo returns the whole collection. Defaults to True; False skips the check, for a server that accepts a name its queryables leave out.

True
resume Checkpoint

Continue a query from a Checkpoint: a page's checkpoint or a PaginationError's (D-52). Its pending requests are sent as stored, so no query keyword may come with it, validate is ignored, and no request it holds is sent again.

None

Yields:

Type Description
Page

One per response, the decoded document in body and its bytes in content. Its checkpoint is where the query stands once the caller holds it.

Raises:

Type Description
ValidationError

Before any request, when collection is empty, ., or .., both bbox and geometry, or ids and filter, are given, ids is a str or bytes, empty, or lacks id_property, bbox or geometry is malformed, a CQL2-JSON filter holds a NaN or infinite number, a filter is empty, params also holds a parameter a keyword sets (bbox, filter, filter-lang) or a credential such as api_key, or limit is not an integer from 1 to the profile's max_limit, or a split is given to a service other than NWIS, both splits are given, or the query has no closed datetime interval or site list to split. With validate, before the first page request, when the collection, a name in params, or id_property is unknown; the message lists the valid ones. With resume, when a query keyword comes with it or it is a checkpoint of another service or collection.

TypeError

Before any request, when a CQL2-JSON filter holds a value JSON cannot encode, such as a set.

ServiceError

With validate, when a metadata request fails.

PaginationError

When a request fails, a body is not a FeatureCollection with well-formed links, or a next link repeats a request already answered, leaves the scheme, host, and port of base_url, or a page has a link that carries a credential (D-53). It is raised once every page that arrived has been yielded; its failures name each such request or link by URL, and its checkpoint is where the query stands.

collect(collection, *, params=None, bbox=None, geometry=None, filter=None, ids=None, id_property=None, split_datetime=None, sites_per_piece=None, validate=True, keep_pages=False, resume=None) async

Fetch every page of a collection's items into one QueryResult (D-22).

Parameters:

Name Type Description Default
collection str

The collection id.

required
params Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
bbox Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
geometry Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
filter Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
ids Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
id_property Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
split_datetime Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
sites_per_piece Mapping[str, str] | None

The query and its pieces, as for iter_pages.

None
validate bool

Check the query against cached metadata first, as for iter_pages.

True
keep_pages bool

Keep each page's response bytes in Page.content (D-23). Page bodies are always dropped. With resume, it applies to the new pages; held pages keep what the earlier call kept.

False
resume QueryResult or Checkpoint

Continue a query that stopped on a failure (D-52): the result of a PartialResultsError, or the checkpoint of a PaginationError raised before any page arrived. The result's pages and features come first in the new result, and no request for them is sent. No query keyword may come with it.

None

Returns:

Type Description
QueryResult

geojson holds the features of all pages in the order they arrived, those of resume first.

Raises:

Type Description
ValidationError

On a malformed query or, with validate, an unknown name, as for iter_pages. With resume, before any request, when a query keyword comes with it, it is from another service or collection, a QueryResult has no checkpoint, or a Checkpoint holds pages, which only the QueryResult that holds them can carry.

TypeError

Before any request, when a CQL2-JSON filter holds a value JSON cannot encode, as for iter_pages.

ServiceError

With validate, when a metadata request fails.

PartialResultsError

When a page fails after at least one succeeded, resume's included. Its result holds the pages that succeeded and the checkpoint to resume.

PaginationError

When no page arrives, as when the first page of an unsplit query fails.

item(collection, item_id, *, params=None, validate=True) async

Fetch one feature of a collection by its id (D-22).

Parameters:

Name Type Description Default
collection str

The collection id.

required
item_id str or int

The feature id, percent-encoded into the URL path.

required
params mapping of str to str

Query parameters, such as crs or skipGeometry, with f=json added unless given.

None
validate bool

Before the request, check collection against the cached collection index, as iter_pages does. Defaults to True.

True

Returns:

Type Description
Page

body holds the decoded Feature and content its bytes. feature_count is 1, and number_matched and number_returned are None.

Raises:

Type Description
ServiceError

If the request fails, with status 404 for an unknown id, or the body is not a Feature whose links member, when present, is a list. With validate, also when the metadata request fails.

ValidationError

Before any request, if collection or item_id is empty, ., or .., which would address another path, or params carries a credential such as api_key. With validate, if the collection is unknown.

aclose() async

Close the transport if this service created it.

NWIS

Bases: OGCService

Async client for the USGS Water Data OGC API, which serves NWIS data (D-42).

Construction performs no HTTP. Pages hold 10,000 features unless params set a limit, and 50,000 at most (D-41).

Parameters:

Name Type Description Default
api_key str

A USGS API key, sent in the X-Api-Key header of every request (D-18). Defaults to the USGS_API_KEY environment variable, read once here. An empty string sends no key.

None
transport Transport

Sends every request, as for OGCService.

None

Raises:

Type Description
ValidationError

If the key holds a character other than printable ASCII, such as a newline.

FabricData

Bases: OGCService

Async client for the USGS FabricData service, which is sent no key (D-30).

Construction performs no HTTP. Pages hold 1,000 features unless params set a smaller limit (D-41).

Parameters:

Name Type Description Default
transport Transport

Sends every request, as for OGCService. Pass Transport(timeout=..., max_retries=...) to tune the timeout and retry count.

None

GeoConnex

Bases: OGCService

Async client for the GeoConnex reference features, which never get the USGS key.

GeoConnex is not a USGS host, so the key never goes there (D-13). Construction performs no HTTP. Pages hold 500 features unless params set a limit, and 10,000 at most (D-41).

Parameters:

Name Type Description Default
transport Transport

Sends every request, as for OGCService. Sharing one with an NWIS service is safe, since the key travels with each NWIS request.

None

Results

An aggregated query result and the pages behind it (D-03).

Parameters:

Name Type Description Default
geojson dict

The aggregated FeatureCollection, nothing coerced. Left out of repr.

required
pages tuple of Page

Every page received, in order. Bodies are None; content holds the bytes only with keep_pages=True (D-23), as set by the call that fetched each page, so a resumed result can mix the two.

required
pagination Pagination

Counts and completeness of the traversal.

required
crs CRS

The requested, per-page, and effective CRS, and how it was determined.

required
checkpoint Checkpoint

Where a query that stopped on a failure stands, for collect(resume=...) (D-52). None once nothing is left to send, and after a refused request, which a resume would refuse again.

None

One response document and the evidence of how it was fetched (D-22).

Parameters:

Name Type Description Default
url str

The request as sent, query included. Credential values are masked, and userinfo and fragment dropped.

required
params mapping of str to str

The caller's query parameters, with credential values masked.

required
status int

HTTP status code.

required
headers mapping of str to str

Response headers in KEPT_HEADERS, with lowercase names.

required
links tuple of Link

Links from the document.

required
fetched_at float

When the response arrived, in seconds since the epoch.

required
number_matched int or None

numberMatched as the server reported it, None when absent.

required
number_returned int or None

numberReturned as the server reported it, None when absent.

required
feature_count int

Features received in this document.

required
body dict

The decoded document, a Feature or a FeatureCollection. The one mutable field; the caller owns it.

None
content bytes

The response body after HTTP content decoding, before JSON decoding.

None
method str

The request's HTTP method, defaults to GET.

'GET'
request_body bytes

The request body as sent, None for a request without one. With method and url it identifies the request (D-38).

None
checkpoint Checkpoint

Where the query stands once the caller holds this page, set on each page iter_pages yields with more left to fetch (D-52). Saving it with the page lets a stopped process resume. None on the last page, on a page whose next link was refused, on item pages, and on the pages of a QueryResult, which carries its own.

None
Notes

params and headers are read-only copies. body and content are the server's document as received, so redaction does not reach them; the key stays out of them because it never travels in a query (D-18).

json()

Decode content into a new object on every call (D-23).

Raises:

Type Description
ValueError

If the page kept no content.

What a traversal fetched and whether it reached the end (D-22).

Parameters:

Name Type Description Default
number_matched int or None

The numberMatched every page reported and agreed on, None when a page left it out or pages disagreed. Pages that report it beside pages that do not leave the result unknown.

required
number_returned int

Features received across all pages.

required
page_count int

Pages received.

required
completeness ('complete', 'limited', 'unknown')

complete when traversal reached the end and every check passed, limited when it stopped early, unknown otherwise.

"complete"
stop_reason ('limit', 'failure')

Why a limited traversal stopped: a caller limit or a failed page.

"limit"
sort_by str

The sort key the pages were requested with.

None
checks tuple of {"end_of_links", "count"}

The completeness checks that ran and passed: the last page had no next link, and the features received equal the agreed numberMatched.

()

Raises:

Type Description
ValueError

If stop_reason is set without limited, or missing with it.

A link from a response document, with credentials masked in href.

Parameters:

Name Type Description Default
href str

Target URL.

required
rel str

Relation type, such as next or self.

None
type str

Media type of the target.

None
title str

Human-readable label.

None
hreflang str

Language of the target.

None
extra mapping of str to Any

Every other member of the link object, read-only and left out of the hash.

empty_extra()

from_dict(doc) classmethod

Parse a link object.

Raises:

Type Description
ValueError

If doc has no string href.

to_dict()

Return the link object, href redacted.

The coordinate reference system of a result and how it was determined (D-37).

Parameters:

Name Type Description Default
requested str or None

The crs query parameter of the first request as sent, None when absent.

required
page_crs tuple of str or None

Each page's Content-Crs header with its angle brackets removed, None for a page without one. A repeated header lists its values comma-separated.

required
effective str or None

The CRS of the geometries, None when no evidence settles it.

required
source ('content_crs', 'default', 'unconfirmed', 'unknown')

content_crs when every page named the same CRS. Without a header on any page: default (CRS84, the OGC API Features default) when no request asked for another CRS, unconfirmed when every request asked for the same other CRS, which a server applying it must name in Content-Crs, and unknown when the requests disagreed. unknown also when pages named different CRSs or only some named one.

"content_crs"

Where an unfinished items query stands: what it holds and what it has left (D-52).

Every yielded Page with more to fetch carries one, as do PaginationError and a QueryResult that stopped early. Pass it to iter_pages(resume=...), or a QueryResult to collect(resume=...). It pickles, holds no feature, and refuses to resume on another service or collection. Unpickle only a checkpoint you saved: loading a pickle runs code, and it skips the checks a Request makes when built.

Parameters:

Name Type Description Default
base_url str

The base_url of the service that ran the query.

required
collection str

The collection the query reads.

required
pending tuple of Request

The requests left to send, in order: the requests that failed, those in flight or fetched and not yet yielded, the next links not yet started, the pieces not yet started, then the refused ones (D-56).

required
held collection of tuple

The identity (method, URL as sent, body) of each request already answered, in the order answered. A resumed query refuses to send any of them again.

frozenset[RequestId]()
malformed bool

Whether an answered page held a numberMatched or numberReturned that is not a non-negative integer, so a resumed QueryResult still reads unknown.

False

Raises:

Type Description
TypeError

If pending holds anything but Request objects.

ValueError

If pending is empty: a query with nothing left has no checkpoint.

One items request: its identity (D-38) and the headers it needs.

A Checkpoint holds the requests a query has still to send (D-52). Construction refuses a credential, so a stored or pickled request never carries one.

Parameters:

Name Type Description Default
url str

The URL before params are added.

required
method str

GET, the default, or POST; every next link is requested the same way.

'GET'
params mapping of str to str

Query parameters of this request only; a next link carries its own.

dict[str, str]()
body bytes

The body, sent to every next link as well.

None
headers mapping of str to str

Accept or Content-Type, sent with every request beside the service's own headers.

None

Raises:

Type Description
ValidationError

If method is not GET or POST, url holds userinfo, url or params carry a credential such as api_key, or headers holds another header. A credential is refused, since masking it would change the request.

Notes

params and headers are read-only copies, so a change to the mappings passed in never reaches a stored request.

identity()

Return the method, URL as sent with credentials masked, and body (D-38).

Collection metadata

The /collections document.

Parameters:

Name Type Description Default
collections tuple of Collection

Every collection, in the server's order.

None
links tuple of Link

Links of the document itself.

None
extra mapping of str to Any

Every other member.

empty_extra()

from_dict(doc) classmethod

Parse the document.

Raises:

Type Description
ValueError

If an entry of collections is not an object with a string id.

to_dict()

Return the document as the server sent it, href redacted in parsed links.

One collection, from /collections or /collections/{id}.

A field is None when the server left its member out or sent it with a shape the field cannot hold, such as a null; that member then stays in extra.

Parameters:

Name Type Description Default
id str

Collection identifier, the path segment in its URLs.

required
title str

Human-readable title.

None
description str

Long description.

None
keywords tuple of str

Keywords.

None
links tuple of Link

Links, href redacted.

None
extent Extent

Spatial and temporal extent.

None
item_type str

itemType, such as feature or record.

None
crs tuple of str

Every CRS the server can return features in.

None
storage_crs str

storageCrs, the CRS the server stores the features in.

None
extra mapping of str to Any

Every other member.

empty_extra()

from_dict(doc) classmethod

Parse a collection document.

Raises:

Type Description
ValueError

If doc has no string id.

to_dict()

Return the document as the server sent it, href redacted in parsed links.

A collection's extent.

Parameters:

Name Type Description Default
spatial SpatialExtent

Bounding boxes.

None
temporal TemporalExtent

Time intervals.

None
extra mapping of str to Any

Every other member.

empty_extra()

from_dict(doc) classmethod

Parse the member.

to_dict()

Return the member as the server sent it.

The spatial member of a collection's extent.

Parameters:

Name Type Description Default
bbox tuple of tuple of float

Every bounding box the server sent, in order: 4 or 6 numbers each. The first covers the whole collection.

None
crs str

CRS of the boxes.

None
extra mapping of str to Any

Every other member.

empty_extra()

from_dict(doc) classmethod

Parse the member.

to_dict()

Return the member as the server sent it.

The temporal member of a collection's extent.

Parameters:

Name Type Description Default
interval tuple of (str or None, str or None)

Every interval the server sent, in order. None marks an open end.

None
trs str

Temporal reference system.

None
extra mapping of str to Any

Every other member.

empty_extra()

from_dict(doc) classmethod

Parse the member.

to_dict()

Return the member as the server sent it.

A /queryables or /schema document.

/queryables lists the properties a query can filter on, /schema the properties a feature carries.

Parameters:

Name Type Description Default
title str

Human-readable title.

None
properties mapping of str to Property

Every property by name, in the server's order. Read-only.

None
extra mapping of str to Any

Every other member, such as $id and $schema.

empty_extra()

from_dict(doc) classmethod

Parse the document.

to_dict()

Return the document as the server sent it.

One property of a /queryables or /schema document, a JSON Schema.

Parameters:

Name Type Description Default
type str

JSON type, such as string or integer.

None
title str

Human-readable name.

None
description str

Long description.

None
format str

Format, such as date-time or geometry-any.

None
role str

x-ogc-role, such as id or primary-geometry.

None
extra mapping of str to Any

Every other member, such as enum or example.

empty_extra()

from_dict(doc) classmethod

Parse the property.

to_dict()

Return the property as the server sent it.

Logging and errors

Set where the package logger writes, replacing the previous configuration.

Each call states the whole configuration: an argument left out returns to its default, so configure_logger(level="DEBUG") after configure_logger(file=...) turns file logging off. configure_logger() restores the import-time setup, a console handler on stderr at WARNING. https://docs.hyriver.io/water-ogcapi/logging/ covers applications with their own logging, AWS Lambda, and tests.

Parameters:

Name Type Description Default
verbose bool

Shortcut for the console level: True is DEBUG, False is WARNING. level wins when both are given.

None
level str or int

Console level, such as "INFO". Defaults to WARNING.

None
file str or Path

Also write to this file, encoded as UTF-8. Parent directories are created.

None
file_level str or int

File level. Defaults to DEBUG.

'DEBUG'
file_mode ('a', 'w')

Append to the file or overwrite it. Defaults to 'a'.

'a'
file_only bool

Write to the file and not the console. Requires file.

False

Raises:

Type Description
ValidationError

If a level or file_mode is invalid, or file_only is set without file. The previous configuration stays in place.

OSError

If the file cannot be opened. The previous configuration stays in place.

Exceptions for water_ogcapi.

WaterOGCAPIError

Bases: Exception

Base exception for all water_ogcapi errors.

ValidationError

Bases: WaterOGCAPIError, ValueError

Raised before a request is sent when caller input is invalid (docs/design.md D-45).

Its message names the valid options where a finite set exists, such as the collections of a service or the properties a query can filter on.

ServiceError

Bases: WaterOGCAPIError

Raised when a request fails: an error status, a redirect, a body of the wrong shape, or a URL refused before sending (attempts 0).

Parameters:

Name Type Description Default
message str

Description of the failure.

required
url str

The URL that triggered the error, included in the message when given, with credential query values masked (D-04).

None
status int

HTTP status code from the failed response, when available.

None
attempts int

Requests made before giving up, defaults to 1; 0 when the request was refused before sending. Anything above 1 means the transport retried, so an outer retry budget can tell a single failure from an exhausted one.

1
retry_after float

Seconds the server asked the caller to wait, parsed from Retry-After.

None
method str

The request's HTTP method, defaults to GET.

'GET'
request_body bytes

The request body as sent, None for a request without one (D-38).

None

RateLimitError

Bases: ServiceError

Raised when an OGC API service returns HTTP 429 Too Many Requests.

Parameters:

Name Type Description Default
message str

Description of the failure.

required
url str

The URL that triggered the error.

None
retry_after float

Seconds to wait before retrying, parsed from the Retry-After header. Both integer-second and HTTP-date forms are supported.

None
remaining int

Value of the x-ratelimit-remaining header when present.

None
attempts int

Requests made before giving up, defaults to 1.

1
method str

The request's HTTP method, defaults to GET.

'GET'
request_body bytes

The request body as sent, None for a request without one (D-38).

None

PaginationError

Bases: WaterOGCAPIError

Raised when page requests of a traversal fail (docs/design.md D-24).

Every page that succeeded has already been yielded, so the error holds no page.

Parameters:

Name Type Description Default
failures sequence of ServiceError

One error per failed request, each naming the request by its URL as sent.

required
checkpoint Checkpoint

Where the query stands, the failed requests first, for resume (D-52). None when nothing but refused requests remains, since a resume would refuse them again.

None

PartialResultsError

Bases: PaginationError

Raised by collect() when a page failed after at least one page succeeded.

Parameters:

Name Type Description Default
failures sequence of ServiceError

One error per failed request, each naming the request by its URL as sent.

required
result QueryResult

Every page that succeeded, with completeness limited and stop reason failure (docs/design.md D-24). Its checkpoint, also this error's, lets collect(resume=result) continue it (D-52).

required