API Reference#

This section is autogenerated from in-line code documentation. It is mostly useful as a reference for the various classes, methods, and other objects in the library, but is not intended to function as a starting point for working with pystac_client.

Client#

Client is the base PySTAC-Client that inherits from Catalog. In addition to the PySTAC functionality, Client allows opening of API URLs, understanding of conformance, and support for searching and paging through results.

class pystac_client.Client(id, description, title=None, stac_extensions=None, extra_fields=None, href=None, catalog_type=CatalogType.ABSOLUTE_PUBLISHED, *, modifier=None, **kwargs)[source]#

Bases: Catalog, QueryablesMixin

A Client for interacting with the root of a STAC Catalog or API

Instances of the Client class inherit from pystac.Catalog and provide a convenient way of interacting with STAC Catalogs OR STAC APIs that conform to the STAC API spec. In addition to being a valid STAC Catalog APIs that have a "conformsTo" indicate that it supports additional functionality on top of a normal STAC Catalog, such as searching items (e.g., /search endpoint).

add_conforms_to(name)[source]#

Add "conformsTo" by name.

Parameters:

name – name of ConformanceClasses keys to add.

clear_conforms_to()[source]#

Clear list of "conformsTo" urls

Removes the entire list, so has_conforms_to() will return False after using this method.

conforms_to(conformance_class)[source]#

Checks whether the API conforms to the given standard.

This method only checks against the "conformsTo" property from the API landing page and does not make any additional calls to a /conformance endpoint even if the API provides such an endpoint.

Parameters:

name – name of ConformanceClasses keys to check conformance against.

Returns:

Indicates if the API conforms to the given spec or URI.

Return type:

bool

classmethod from_dict(d, href=None, root=None, migrate=False, preserve_dict=True, modifier=None)[source]#

Parses this STACObject from the passed in dictionary.

Parameters:
  • d – The dict to parse.

  • href – Optional href that is the file location of the object being parsed.

  • root – Optional root catalog for this object. If provided, the root of the returned STACObject will be set to this parameter.

  • migrate – Use True if this dict represents JSON from an older STAC object, so that migrations are run against it.

  • preserve_dict – If False, the dict parameter d may be modified during this method call. Otherwise the dict is not mutated. Defaults to True, which results results in a deepcopy of the parameter. Set to False when possible to avoid the performance hit of a deepcopy.

Returns:

The STACObject parsed from this dict.

Return type:

STACObject

classmethod from_file(href, stac_io=None, headers=None, parameters=None, modifier=None, request_modifier=None, timeout=None)[source]#

Open a STAC Catalog/API

Returns:

A Client (PySTAC Catalog) of the root Catalog for this Catalog/API

Return type:

Client

get_all_items()[source]#

Get all items from this catalog and all subcatalogs. Will traverse any subcatalogs recursively, or use the /search endpoint if supported

Returns:

All items that belong to this catalog, and all

catalogs or collections connected to this catalog through child links.

Return type:

Iterator[Item]

get_collection(collection_id)[source]#

Get a single collection from this Catalog/API

Parameters:

collection_id – The Collection ID to get

Returns:

A STAC Collection

Return type:

Union[Collection, CollectionClient]

Raises:

NotFoundError if collection_id does not exist.

get_collections()[source]#

Get Collections in this Catalog

Gets the collections from the /collections endpoint if supported, otherwise fall back to Catalog behavior of following child links

Returns:

Collections in Catalog/API

Return type:

Iterator[Union[Collection, CollectionClient]]

get_conforms_to()[source]#

List of "conformsTo" URIs

Returns:

List of URIs that the server conforms to

Return type:

List[str]

get_items(*ids, recursive=None)[source]#

Return all items of this catalog.

Parameters:
  • ids – Zero or more item ids to find.

  • recursive – unused in pystac-client, but needed for falling back to pystac

Returns:

Iterator of items whose parent is this

catalog.

Return type:

Iterator[Item]

get_merged_queryables(collections)[source]#

Return the set of queryables in common to the specified collections.

Queryables from multiple collections are unioned together, except in the case when the same queryable key has a different definition, in which case that key is dropped.

Output is a dictionary that can be used in jsonshema.validate

Parameters:

List[str] (collections) – The IDs of the collections to inspect.

Returns:

Dictionary containing queryable fields

Return type:

Dict[str, Any]

Returns this client’s search link.

Searches for a link with rel=”search” and either a GEOJSON or JSON media type.

Returns:

The search link, or None if there is not one found.

Return type:

Optional[pystac.Link]

has_conforms_to()[source]#

Whether server contains list of "conformsTo" URIs

classmethod open(url, headers=None, parameters=None, ignore_conformance=None, modifier=None, request_modifier=None, stac_io=None, timeout=None)[source]#

Opens a STAC Catalog or API This function will read the root catalog of a STAC Catalog or API

Parameters:
  • url – The URL of a STAC Catalog.

  • headers – A dictionary of additional headers to use in all requests made to any part of this Catalog/API.

  • parameters – Optional dictionary of query string parameters to include in all requests.

  • ignore_conformance (DEPRECATED) –

    Ignore any advertised Conformance Classes in this Catalog/API. This means that functions will skip checking conformance, and may throw an unknown error if that feature is not supported, rather than a NotImplementedError.

    Deprecated since version 0.7.0: Conformance can be altered rather than ignored using methods like clear_conforms_to() and add_conforms_to()

  • modifier

    A callable that modifies the children collection and items returned by this Client. This can be useful for injecting authentication parameters into child assets to access data from non-public sources.

    The callable should expect a single argument, which will be one of the following types:

    The callable should mutate the argument in place and return None.

    modifier propagates recursively to children of this Client. After getting a child collection with, e.g. Client.get_collection(), the child items of that collection will still be signed with modifier.

  • request_modifier

    A callable that either modifies a Request instance or returns a new one. This can be useful for injecting Authentication headers and/or signing fully-formed requests (e.g. signing requests using AWS SigV4).

    The callable should expect a single argument, which will be an instance of requests.Request.

    If the callable returns a requests.Request, that will be used. Alternately, the callable may simply modify the provided request object and return None.

  • stac_io – A StacApiIO object to use for I/O requests. Generally, leave this to the default. However in cases where customized I/O processing is required, a custom instance can be provided here.

  • timeout – Optional float or (float, float) tuple following the semantics defined by Requests.

Returns:

A Client instance for this Catalog/API

Return type:

catalog

remove_conforms_to(name)[source]#

Remove "conformsTo" by name.

Parameters:

name – name of ConformanceClasses keys to remove.

search(*, method='POST', max_items=None, limit=None, ids=None, collections=None, bbox=None, intersects=None, datetime=None, query=None, filter=None, filter_lang=None, sortby=None, fields=None)[source]#

Query the /search endpoint using the given parameters.

This method returns an ItemSearch instance. See that class’s documentation for details on how to get the number of matches and iterate over results. The url, stac_io`, and client keywords are supplied by this Client instance.

Warning

This method is only implemented if the API conforms to the STAC API - Item Search spec and contains a link with a "rel" type of "search" in its root catalog. If the API does not meet either of these criteria, this method will raise a NotImplementedError.

Parameters:
  • method – The HTTP method to use when making a request to the service. This must be either "GET", "POST", or None. If None, this will default to "POST". If a "POST" request receives a 405 status for the response, it will automatically retry with "GET" for all subsequent requests.

  • max_items – The maximum number of items to return from the search, even if there are more matching results. This client to limit the total number of Items returned from the items(), item_collections(), and items_as_dicts methods(). The client will continue to request pages of items until the number of max items is reached. This parameter defaults to 100. Setting this to None will allow iteration over a possibly very large number of results.

  • limit – A recommendation to the service as to the number of items to return per page of results. Defaults to 100.

  • ids – List of one or more Item ids to filter on.

  • collections – List of one or more Collection IDs or pystac.Collection instances. Only Items in one of the provided Collections will be searched

  • bbox – A list, tuple, or iterator representing a bounding box of 2D or 3D coordinates. Results will be filtered to only those intersecting the bounding box.

  • intersects – A string or dictionary representing a GeoJSON geometry, or an object that implements a __geo_interface__ property, as supported by several libraries including Shapely, ArcPy, PySAL, and geojson. Results filtered to only those intersecting the geometry.

  • datetime

    Either a single datetime or datetime range used to filter results. You may express a single datetime using a datetime.datetime instance, a RFC 3339-compliant timestamp, or a simple date string (see below). Instances of datetime.datetime may be either timezone aware or unaware. Timezone aware instances will be converted to a UTC timestamp before being passed to the endpoint. Timezone unaware instances are assumed to represent UTC timestamps. You may represent a datetime range using a "/" separated string as described in the spec, or a list, tuple, or iterator of 2 timestamps or datetime instances. For open-ended ranges, use either ".." ('2020-01-01:00:00:00Z/..', ['2020-01-01:00:00:00Z', '..']) or a value of None (['2020-01-01:00:00:00Z', None]).

    If using a simple date string, the datetime can be specified in YYYY-mm-dd format, optionally truncating to YYYY-mm or just YYYY. Simple date strings will be expanded to include the entire time period, for example:

    • 2017 expands to 2017-01-01T00:00:00Z/2017-12-31T23:59:59Z

    • 2017-06 expands to 2017-06-01T00:00:00Z/2017-06-30T23:59:59Z

    • 2017-06-10 expands to 2017-06-10T00:00:00Z/2017-06-10T23:59:59Z

    If used in a range, the end of the range expands to the end of that day/month/year, for example:

    • 2017/2018 expands to 2017-01-01T00:00:00Z/2018-12-31T23:59:59Z

    • 2017-06/2017-07 expands to 2017-06-01T00:00:00Z/2017-07-31T23:59:59Z

    • 2017-06-10/2017-06-11 expands to 2017-06-10T00:00:00Z/2017-06-11T23:59:59Z

  • query – List or JSON of query parameters as per the STAC API query extension

  • filter – JSON of query parameters as per the STAC API filter extension

  • filter_lang – Language variant used in the filter body. If filter is a dictionary or not provided, defaults to ‘cql2-json’. If filter is a string, defaults to cql2-text.

  • sortby – A single field or list of fields to sort the response by

  • fields – A list of fields to include in the response. Note this may result in invalid STAC objects, as they may not have required fields. Use items_as_dicts to avoid object unmarshalling errors.

Returns:

An ItemSearch instance that can be used to iterate through Items.

Return type:

search

Raises:

NotImplementedError – If the API does not conform to the Item Search spec or does not have a link with a "rel" type of "search".

set_conforms_to(conformance_uris)[source]#

Set list of "conformsTo" URIs

Parameters:

conformance_uris – URIs indicating what the server conforms to

Collection Client#

Client is the a PySTAC-Client that inherits from Collection. In addition to the PySTAC functionality, CollectionClient allows opening of API URLs, and iterating through items at a search endpoint, if supported.

class pystac_client.CollectionClient(id, description, extent, title=None, stac_extensions=None, href=None, extra_fields=None, catalog_type=None, license='proprietary', keywords=None, providers=None, summaries=None, *, modifier=None, **kwargs)[source]#
conforms_to(conformance_class)[source]#
classmethod from_dict(d, href=None, root=None, migrate=False, preserve_dict=True, modifier=None)[source]#

Parses this STACObject from the passed in dictionary.

Parameters:
  • d – The dict to parse.

  • href – Optional href that is the file location of the object being parsed.

  • root – Optional root catalog for this object. If provided, the root of the returned STACObject will be set to this parameter.

  • migrate – Use True if this dict represents JSON from an older STAC object, so that migrations are run against it.

  • preserve_dict – If False, the dict parameter d may be modified during this method call. Otherwise the dict is not mutated. Defaults to True, which results results in a deepcopy of the parameter. Set to False when possible to avoid the performance hit of a deepcopy.

Returns:

The STACObject parsed from this dict.

Return type:

STACObject

get_item(id, recursive=False)[source]#

Returns an item with a given ID.

If the collection conforms to [ogcapi-features](radiantearth/stac-api-spec), this will use the /collections/{collectionId}/items/{featureId}. If not, and the collection conforms to [item search](radiantearth/stac-api-spec), this will use /search?ids={featureId}&collections={collectionId}. Otherwise, the default PySTAC behavior is used.

Parameters:
  • id – The ID of the item to find.

  • recursive – If True, search this catalog and all children for the item; otherwise, only search the items of this catalog. Defaults to False.

Returns:

The item with the given ID, or None if not found.

Return type:

Item or None

get_items(*ids, recursive=False)[source]#

Return all items in this Collection or specific items.

If the Collection contains a link of with a rel value of items, that link will be used to iterate through items. Otherwise, the default PySTAC behavior is assumed.

Parameters:
  • ids – Items ids to retrieve

  • recursive – If True, search every child collection as well as this one.

Returns:

Iterator of items whose parent is this catalog.

Return type:

Iterator[Item]

get_root()[source]#

Get the Catalog or Collection to the root for this object. The root is represented by a Link with rel == 'root'.

Returns:

The root object for this object, or None if no root link is set.

Return type:

Catalog, Collection, or None

modifier#
set_root(root)[source]#

Sets the root Catalog or Collection for this object.

Parameters:

root – The root object to set. Passing in None will clear the root.

STAC API IO#

The StacApiIO class inherits from the Collection class and allows for reading over http, such as with REST APIs.

class pystac_client.stac_api_io.StacApiIO(headers=None, conformance=None, parameters=None, request_modifier=None, timeout=None, max_retries=5)[source]#

Bases: DefaultStacIO

get_pages(url, method=None, parameters=None)[source]#

Iterator that yields dictionaries for each page at a STAC paging endpoint, e.g., /collections, /search

Returns:

JSON content from a single page

Return type:

Dict[str, Any]

read_text(source, *args, **kwargs)[source]#

Read text from the given URI.

Overwrites the default method for reading text from a URL or file to allow urllib.request.Request instances as input. This method also raises any urllib.error.HTTPError exceptions rather than catching them to allow us to handle different response status codes as needed.

request(href, method=None, headers=None, parameters=None)[source]#

Makes a request to an http endpoint

Parameters:
  • href (str) – The request URL

  • method (Optional[str], optional) – The http method to use, ‘GET’ or ‘POST’. Defaults to None, which will result in ‘GET’ being used.

  • headers (Optional[Dict[str, str]], optional) – Additional headers to include in request. Defaults to None.

  • parameters (Optional[Dict[str, Any]], optional) – parameters to send with request. Defaults to None.

Raises:

APIError – raised if the server returns an error response

Returns:

The decoded response from the endpoint

Return type:

str

stac_object_from_dict(d, href=None, root=None, preserve_dict=True)[source]#

Deserializes a STACObject sub-class instance from a dictionary.

Parameters:
  • d – The dictionary to deserialize

  • href – Optional href to associate with the STAC object

  • root – Optional root Catalog to associate with the STAC object.

  • preserve_dict – If False, the dict parameter d may be modified during this method call. Otherwise the dict is not mutated. Defaults to True, which results results in a deepcopy of the parameter. Set to False when possible to avoid the performance hit of a deepcopy.

update(headers=None, parameters=None, request_modifier=None, timeout=None)[source]#

Updates this StacApi’s headers, parameters, and/or request_modifer.

Parameters:
  • headers – Optional dictionary of headers to include in all requests

  • parameters – Optional dictionary of query string parameters to include in all requests.

  • request_modifier – Optional callable that can be used to modify Request objects before they are sent. If provided, the callable receives a request.Request and must either modify the object directly or return a new / modified request instance.

  • timeout – Optional float or (float, float) tuple following the semantics defined by Requests.

write_text_to_href(href, *args, **kwargs)[source]#

Writes text to file using UTF-8 encoding.

This implementation uses open() and therefore can only write to the local file system.

Parameters:
  • href – The path to which the file will be written.

  • txt – The string content to write to the file.

Conformance#

class pystac_client.conformance.ConformanceClasses(value)[source]#

Bases: Enum

Enumeration class for Conformance Classes

COLLECTIONS = '/collections'#
CONTEXT = '/item-search#context'#
CORE = '/core'#
FEATURES = '/ogcapi-features'#
FIELDS = '/item-search#fields'#
FILTER = '/item-search#filter'#
QUERY = '/item-search#query'#
SORT = '/item-search#sort'#
classmethod get_by_name(name)[source]#
property pattern#
property valid_uri#

Exceptions#

exception pystac_client.exceptions.APIError[source]#

Bases: Exception

Raised when unexpected server error.

classmethod from_response(response)[source]#
status_code#
exception pystac_client.exceptions.ParametersError[source]#

Bases: Exception

Raised when invalid parameters are used in a query

Warnings#

exception pystac_client.warnings.DoesNotConformTo[source]#

Bases: PystacClientWarning

Inform user when client does not conform to extension

exception pystac_client.warnings.FallbackToPystac[source]#

Bases: PystacClientWarning

Inform user when falling back to pystac implementation

Bases: PystacClientWarning

Inform user when link is not found

exception pystac_client.warnings.NoConformsTo[source]#

Bases: PystacClientWarning

Inform user when client does not have “conformsTo” set

exception pystac_client.warnings.PystacClientWarning[source]#

Bases: UserWarning

Base warning class

pystac_client.warnings.ignore()[source]#

Context manager for ignoring all pystac-client warnings

For more fine-grained control or to set filter warnings in the whole python session, use the warnings module directly.

Examples:

>>> from pystac_client import Client
>>> from pystac_client.warnings import ignore
>>> with ignore():
...     Client.open("https://perfect-api.test")

For finer-grained control:

>>> import warnings
>>> from pystac_client import Client
>>> from pystac_client.warnings import MissingLink
>>> warnings.filterwarnings("ignore", category=MissingLink)
>>> Client.open("https://imperfect-api.test")
pystac_client.warnings.strict()[source]#

Context manager for raising all pystac-client warnings as errors

For more fine-grained control or to filter warnings in the whole python session, use the warnings module directly.

Examples:

>>> from pystac_client import Client
>>> from pystac_client.warnings import strict
>>> with strict():
...     Client.open("https://perfect-api.test")

For finer-grained control:

>>> import warnings
>>> from pystac_client import Client
>>> from pystac_client.warnings import MissingLink
>>> warnings.filterwarnings("error", category=FallbackToPystac)
>>> Client.open("https://imperfect-api.test")