pystac#
PySTAC is a library for working with SpatioTemporal Asset Catalogs (STACs)
- pystac.get_stac_version() str [source]#
Returns the STAC version PySTAC writes as the “stac_version” property for any object it serializes into JSON.
If a call to
set_stac_version
was made, this will return the value it was called with. Next it will check the environment for a PYSTAC_STAC_VERSION_OVERRIDE variable. Otherwise it will return the latest STAC version that this version of PySTAC supports.- Returns
The STAC Version PySTAC is set up to use.
- Return type
- pystac.read_dict(d: Dict[str, Any], href: Optional[str] = None, root: Optional[Catalog] = None, stac_io: Optional[StacIO] = None) STACObject [source]#
Reads a
STACObject
orItemCollection
from a JSON-like dict representing a serialized STAC object.This method will return either a
Catalog
,Collection
, or :class`~Item` based on the contents of the dict.This is a convenience method for either
StacIO.stac_object_from_dict
.- Parameters
d – The dict to parse.
href – Optional href that is the file location of the object being parsed.
root – Optional root of the catalog for this object. If provided, the root’s resolved object cache can be used to search for previously resolved instances of the STAC object.
stac_io – Optional
StacIO
instance to use for reading. IfNone
, the default instance will be used.
- Raises
STACTypeError – If the
d
dictionary does not represent a validSTACObject
. Note that anItemCollection
is not aSTACObject
and must be read usingItemCollection.from_dict
- pystac.read_file(href: Union[str, PathLike], stac_io: Optional[StacIO] = None) STACObject [source]#
Reads a STAC object from a file.
This method will return either a Catalog, a Collection, or an Item based on what the file contains.
This is a convenience method for
StacIO.read_stac_object
- Parameters
href – The HREF to read the object from.
stac_io – Optional
StacIO
instance to use for I/O operations. If not provided, will useStacIO.default()
to create an instance.
- Returns
The specific STACObject implementation class that is represented by the JSON read from the file located at HREF.
- Raises
STACTypeError – If the file at
href
does not represent a validSTACObject
. Note that anItemCollection
is not aSTACObject
and must be read usingItemCollection.from_file
- pystac.set_stac_version(stac_version: Optional[str]) None [source]#
Sets the STAC version that PySTAC should use.
This is the version that will be set as the “stac_version” property on any JSON STAC objects written by PySTAC. If set to None, the override version will be cleared if previously set and the default or an override taken from the environment will be used.
You can also set the environment variable PYSTAC_STAC_VERSION_OVERRIDE to override the version.
- Parameters
stac_version – The STAC version to use instead of the latest STAC version that PySTAC supports (described in STACVersion.DEFAULT_STAC_VERSION). If None, clear to use the default for this version of PySTAC.
Note
Setting the STAC version to something besides the default version will not effect the format of STAC read or written; it will only override the
stac_version
property of the objects being written. Setting this incorrectly can produce invalid STAC.
- pystac.write_file(obj: STACObject, include_self_link: bool = True, dest_href: Optional[Union[str, PathLike]] = None, stac_io: Optional[StacIO] = None) None [source]#
Writes a STACObject to a file.
This will write only the Catalog, Collection or Item
obj
. It will not attempt to write any other objects that are linked toobj
; if you’d like functionality to save off catalogs recursively seeCatalog.save
.This method will write the JSON of the object to the object’s assigned “self” link or to the dest_href if provided. To set the self link, see
STACObject.set_self_href
.Convenience method for
STACObject.from_file
- Parameters
obj – The STACObject to save.
include_self_link – If
True
, include the"self"
link with this object. Otherwise, leave out the self link.dest_href – Optional HREF to save the file to. If
None
, the object will be saved to the object’s"self"
href.stac_io – Optional
StacIO
instance to use for I/O operations. If not provided, will useStacIO.default()
to create an instance.
STACObject#
- class pystac.STACObject(stac_extensions: List[str])[source]#
A base class for other PySTAC classes that contains a variety of useful methods for dealing with links, copying objects, accessing extensions, and reading and writing files. You shouldn’t use STACObject directly, but instead access this functionality through the implementing classes.
- STAC_OBJECT_TYPE: STACObjectType#
- add_link(link: Link) None [source]#
Add a link to this object’s set of links.
- Parameters
link – The link to add.
- add_links(links: List[Link]) None [source]#
Add links to this object’s set of links.
- Parameters
links – The links to add.
- clear_links(rel: Optional[Union[str, RelType]] = None) None [source]#
Clears all
Link
instances associated with this object.- Parameters
rel – If set, only clear links that match this relationship.
- abstract clone() STACObject [source]#
Clones this object.
Cloning an object will make a copy of all properties and links of the object; however, it will not make copies of the targets of links (i.e. it is not a deep copy). To copy a STACObject fully, with all linked elements also copied, use
STACObject.full_copy
.- Returns
The clone of this object.
- Return type
- abstract classmethod from_dict(d: Dict[str, Any], href: Optional[str] = None, root: Optional[Catalog] = None, migrate: bool = False, preserve_dict: bool = True) S [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
- classmethod from_file(href: str, stac_io: Optional[StacIO] = None) S [source]#
Reads a STACObject implementation from a file.
- Parameters
href – The HREF to read the object from.
stac_io – Optional instance of StacIO to use. If not provided, will use the default instance.
- Returns
The specific STACObject implementation class that is represented by the JSON read from the file located at HREF.
- full_copy(root: Optional[Catalog] = None, parent: Optional[Catalog] = None) STACObject [source]#
Create a full copy of this STAC object and any stac objects linked to by this object.
- Parameters
root – Optional root to set as the root of the copied object, and any other copies that are contained by this object.
parent – Optional parent to set as the parent of the copy of this object.
- Returns
A full copy of this object, as well as any objects this object links to.
- Return type
- get_links(rel: Optional[Union[str, RelType]] = None, media_type: Optional[Union[str, MediaType]] = None) List[Link] [source]#
Gets the
Link
instances associated with this object.- Parameters
rel – If set, filter links such that only those matching this relationship are returned.
media_type – If set, filter the links such that only those matching media_type are returned
- Returns
A list of links that match
rel
and/ ormedia_type
if set, or else all links associated with this object.- Return type
List[
Link
]
- get_parent() Optional[Catalog] [source]#
Get the
Catalog
orCollection
to the parent for this object. The root is represented by aLink
withrel == 'parent'
.- Returns
The parent object for this object, or
None
if no root link is set.- Return type
Catalog, Collection, or None
- get_root() Optional[Catalog] [source]#
Get the
Catalog
orCollection
to the root for this object. The root is represented by aLink
withrel == 'root'
.- Returns
The root object for this object, or
None
if no root link is set.- Return type
Catalog, Collection, or None
- get_root_link() Optional[Link] [source]#
Get the
Link
representing the root for this object.- Returns
The root link for this object, or
None
if no root link is set.- Return type
Link
or None
- get_self_href() Optional[str] [source]#
Gets the absolute HREF that is represented by the
rel == 'self'
Link
.- Returns
The absolute HREF of this object, or
None
if there is no self link defined.- Return type
str or None
Note
A self link can exist for objects, even if the link is not read or written to the JSON-serialized version of the object. Any object read from
STACObject.from_file
will have the HREF the file was read from set as it’s self HREF. All self links have absolute (as opposed to relative) HREFs.
- get_single_link(rel: Optional[Union[str, RelType]] = None, media_type: Optional[Union[str, MediaType]] = None) Optional[Link] [source]#
Get a single
Link
instance associated with this object.- Parameters
rel – If set, filter links such that only those matching this relationship are returned.
media_type – If set, filter the links such that only those matching media_type are returned
- Returns
First link that matches
rel
and/ormedia_type
, or else the first link associated with this object.- Return type
Optional[
Link
]
- get_stac_objects(rel: Union[str, RelType], typ: Optional[Type[STACObject]] = None, modify_links: Optional[Callable[[List[Link]], List[Link]]] = None) Iterable[STACObject] [source]#
Gets the
STACObject
instances that are linked to by links with theirrel
property matching the passed in argument.- Parameters
rel – The relation to match each
Link
’srel
property against.typ – If not
None
, objects will only be yielded if they are instances oftyp
.modify_links – A function that modifies the list of links before they are iterated over. For instance, this option can be used to sort the list so that links matching a particular pattern are earlier in the iterator.
- Returns
A possibly empty iterable of STACObjects that are connected to this object through links with the given
rel
and are of typetyp
(if given).- Return type
Iterable[STACObjects]
- abstract classmethod matches_object_type(d: Dict[str, Any]) bool [source]#
Returns a boolean indicating whether the given dictionary represents a valid instance of this
STACObject
sub-class.- Parameters
d – A dictionary to identify
- remove_hierarchical_links(add_canonical: bool = False) List[Link] [source]#
Removes all hierarchical links from this object.
See
pystac.link.HIERARCHICAL_LINKS
for a list of all hierarchical links. If the object has aself
href andadd_canonical
is True, a link withrel="canonical"
is added.- Parameters
add_canonical – If true, and this item has a
self
href, that href is used to build acanonical
link.- Returns
All removed links
- Return type
List[Link]
- remove_links(rel: Union[str, RelType]) None [source]#
Remove links to this object’s set of links that match the given
rel
.- Parameters
rel – The
Link
rel
to match on.
- resolve_links() None [source]#
Ensure all STACObjects linked to by this STACObject are resolved. This is important for operations such as changing HREFs.
This method mutates the entire catalog tree.
- save_object(include_self_link: bool = True, dest_href: Optional[str] = None, stac_io: Optional[StacIO] = None) None [source]#
Saves this STAC Object to it’s ‘self’ HREF.
- Parameters
include_self_link – If this is true, include the ‘self’ link with this object. Otherwise, leave out the self link.
dest_href – Optional HREF to save the file to. If None, the object will be saved to the object’s self href.
stac_io – Optional instance of StacIO to use. If not provided, will use the instance set on the object’s root if available, otherwise will use the default instance.
- Raises
STACError – If no self href is set, this error will be
raised. –
Note
When to include a self link is described in the Use of Links section of the STAC best practices document
- property self_href: str#
Gets the absolute HREF that is represented by the
rel == 'self'
Link
.- Raises
ValueError – If the self_href is not set, this method will throw a ValueError. Use get_self_href if there may not be an href set.
- set_parent(parent: Optional[Catalog]) None [source]#
Sets the parent
Catalog
orCollection
for this object.- Parameters
parent – The parent object to set. Passing in None will clear the parent.
- set_root(root: Optional[Catalog]) None [source]#
Sets the root
Catalog
orCollection
for this object.- Parameters
root – The root object to set. Passing in None will clear the root.
- set_self_href(href: Optional[str]) None [source]#
Sets the absolute HREF that is represented by the
rel == 'self'
Link
.- Parameters
href – The absolute HREF of this object. If the given HREF is not absolute, it will be transformed to an absolute HREF based on the current working directory. If this is None the call will clear the self HREF link.
- stac_extensions: List[str]#
A list of schema URIs for STAC Extensions implemented by this STAC Object.
- abstract to_dict(include_self_link: bool = True, transform_hrefs: bool = True) Dict[str, Any] [source]#
Generate a dictionary representing the JSON of this serialized object.
- Parameters
include_self_link – If True, the dict will contain a self link to this object. If False, the self link will be omitted.
transform_hrefs – If True, transform the HREF of hierarchical links based on the type of catalog this object belongs to (if any). I.e. if this object belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, hierarchical link HREFs will be transformed to be relative to the catalog root.
dict – A serialization of the object that can be written out as JSON.
Catalog#
- class pystac.Catalog(id: str, description: str, title: Optional[str] = None, stac_extensions: Optional[List[str]] = None, extra_fields: Optional[Dict[str, Any]] = None, href: Optional[str] = None, catalog_type: CatalogType = CatalogType.ABSOLUTE_PUBLISHED)[source]#
Bases:
STACObject
A PySTAC Catalog represents a STAC catalog in memory.
A Catalog is a
STACObject
that may contain children, which are instances ofCatalog
orCollection
, as well asItem
s.- Parameters
id – Identifier for the catalog. Must be unique within the STAC.
description – Detailed multi-line description to fully explain the catalog. CommonMark 0.29 syntax MAY be used for rich text representation.
title – Optional short descriptive one-line title for the catalog.
stac_extensions – Optional list of extensions the Catalog implements.
href – Optional HREF for this catalog, which be set as the catalog’s self link’s HREF.
catalog_type – Optional catalog type for this catalog. Must be one of the values in
CatalogType
.
- DEFAULT_FILE_NAME = 'catalog.json'#
Default file name that will be given to this STAC object in a canonical format.
- STAC_OBJECT_TYPE: STACObjectType = 'Catalog'#
- add_child(child: Union['Catalog', Collection], title: Optional[str] = None, strategy: Optional[HrefLayoutStrategy] = None) None [source]#
Adds a link to a child
Catalog
orCollection
. This method will set the child’s parent to this object, and its root to this Catalog’s root.- Parameters
child – The child to add.
title – Optional title to give to the
Link
strategy – The layout strategy to use for setting the self href of the child. If not provided, defaults to
BestPracticesLayoutStrategy
.
- add_children(children: Iterable[Union['Catalog', Collection]]) None [source]#
Adds links to multiple
Catalog
or ~pystac.Collection objects. This method will set each child’s parent to this object, and their root to this Catalog’s root.- Parameters
children – The children to add.
- add_item(item: Item, title: Optional[str] = None, strategy: Optional[HrefLayoutStrategy] = None) None [source]#
Adds a link to an
Item
. This method will set the item’s parent to this object, and its root to this Catalog’s root.- Parameters
item – The item to add.
title – Optional title to give to the
Link
strategy – The layout strategy to use for setting the self href of the item. If not provided, defaults to
BestPracticesLayoutStrategy
.
- add_items(items: Iterable[Item], strategy: Optional[HrefLayoutStrategy] = None) None [source]#
Adds links to multiple
Items
.This method will set each item’s parent to this object, and their root to this Catalog’s root.
- Parameters
items – The items to add.
strategy – The layout strategy to use for setting the self href of the items. If not provided, defaults to
BestPracticesLayoutStrategy
.
- catalog_type: CatalogType#
The catalog type. Defaults to
CatalogType.ABSOLUTE_PUBLISHED
.
- clear_children() None [source]#
Removes all children from this catalog.
- Returns
Returns
self
- Return type
- clone() Catalog [source]#
Clones this object.
Cloning an object will make a copy of all properties and links of the object; however, it will not make copies of the targets of links (i.e. it is not a deep copy). To copy a STACObject fully, with all linked elements also copied, use
STACObject.full_copy
.- Returns
The clone of this object.
- Return type
- describe(include_hrefs: bool = False, _indent: int = 0) None [source]#
Prints out information about this Catalog and all contained STACObjects.
- Parameters
include_hrefs (bool) – HREF along with the object ID.
- extra_fields: Dict[str, Any]#
Extra fields that are part of the top-level JSON properties of the Catalog.
- classmethod from_dict(d: Dict[str, Any], href: Optional[str] = None, root: Optional[Catalog] = None, migrate: bool = False, preserve_dict: bool = True) C [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
- classmethod from_file(href: str, stac_io: Optional[StacIO] = None) C [source]#
Reads a STACObject implementation from a file.
- Parameters
href – The HREF to read the object from.
stac_io – Optional instance of StacIO to use. If not provided, will use the default instance.
- Returns
The specific STACObject implementation class that is represented by the JSON read from the file located at HREF.
- full_copy(root: Optional[Catalog] = None, parent: Optional[Catalog] = None) Catalog [source]#
Create a full copy of this STAC object and any stac objects linked to by this object.
- Parameters
root – Optional root to set as the root of the copied object, and any other copies that are contained by this object.
parent – Optional parent to set as the parent of the copy of this object.
- Returns
A full copy of this object, as well as any objects this object links to.
- Return type
- fully_resolve() None [source]#
Resolves every link in this catalog.
Useful if, e.g., you’d like to read a catalog from a filesystem, upgrade every object in the catalog to the latest STAC version, and save it back to the filesystem. By default,
save()
skips unresolved links.
- generate_subcatalogs(template: str, defaults: Optional[Dict[str, Any]] = None, parent_ids: Optional[List[str]] = None) List[Catalog] [source]#
Walks through the catalog and generates subcatalogs for items based on the template string.
See
LayoutTemplate
for details on the construction of template strings. This template string will be applied to the items, and subcatalogs will be created that separate and organize the items based on template values.- Parameters
template – A template string that can be consumed by a
LayoutTemplate
defaults – Default values for the template variables that will be used if the property cannot be found on the item.
parent_ids – Optional list of the parent catalogs’ identifiers. If the bottom-most subcatalogs already match the template, no subcatalog is added.
- Returns
List of new catalogs created
- Return type
[catalog]
- get_all_collections() Iterable[Collection] [source]#
Get all collections from this catalog and all subcatalogs. Will traverse any subcatalogs recursively.
- get_all_items() Iterable[Item] [source]#
Get all items from this catalog and all subcatalogs. Will traverse any subcatalogs recursively.
- Returns
- All items that belong to this catalog, and all
catalogs or collections connected to this catalog through child links.
- Return type
Generator[Item]
- get_child(id: str, recursive: bool = False, sort_links_by_id: bool = True) Optional[Union['Catalog', Collection]] [source]#
Gets the child of this catalog with the given ID, if it exists.
- Parameters
id – The ID of the child to find.
recursive – If True, search this catalog and all children for the item; otherwise, only search the children of this catalog. Defaults to False.
sort_links_by_id – If True, links containing the ID will be checked first. If links do not contain the ID then setting this to False will improve performance. Defaults to True.
- Returns
The child with the given ID, or None if not found.
- Return type
Optional Catalog or Collection
- get_child_links() List[Link] [source]#
Return all child links of this catalog.
- Returns
List of links of this catalog with
rel == 'child'
- Return type
List[Link]
- get_children() Iterable[Union['Catalog', Collection]] [source]#
Return all children of this catalog.
- Returns
Iterable of children who’s parent is this catalog.
- Return type
Iterable[Catalog or Collection]
- get_collections() Iterable[Collection] [source]#
Return all children of this catalog that are
Collection
instances.
- get_item(id: str, recursive: bool = False) Optional[Item] [source]#
Returns an item with a given ID.
- 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_item_links() List[Link] [source]#
Return all item links of this catalog.
- Returns
List of links of this catalog with
rel == 'item'
- Return type
List[Link]
- get_items() Iterable[Item] [source]#
Return all items of this catalog.
- Returns
Generator of items whose parent is this catalog.
- Return type
Iterable[Item]
- make_all_asset_hrefs_absolute() None [source]#
Makes all the HREFs of assets belonging to items in this catalog and all children to be absolute, recursively.
- make_all_asset_hrefs_relative() None [source]#
Makes all the HREFs of assets belonging to items in this catalog and all children to be relative, recursively.
- map_assets(asset_mapper: Callable[[str, Asset], Union[Asset, Tuple[str, Asset], Dict[str, Asset]]]) Catalog [source]#
Creates a copy of a catalog, with each Asset for each Item passed through the asset_mapper function.
- Parameters
asset_mapper – A function that takes in an key and an Asset, and returns either an Asset, a (key, Asset), or a dictionary of Assets with unique keys. The Asset that is passed into the item_mapper is a copy, so the method can mutate it safely.
- Returns
A full copy of this catalog, with assets manipulated according to the asset_mapper function.
- Return type
- map_items(item_mapper: Callable[[Item], Union[Item, List[Item]]]) Catalog [source]#
Creates a copy of a catalog, with each item passed through the item_mapper function.
- Parameters
item_mapper – A function that takes in an item, and returns either an item or list of items. The item that is passed into the item_mapper is a copy, so the method can mutate it safely.
- Returns
A full copy of this catalog, with items manipulated according to the item_mapper function.
- Return type
- classmethod matches_object_type(d: Dict[str, Any]) bool [source]#
Returns a boolean indicating whether the given dictionary represents a valid instance of this
STACObject
sub-class.- Parameters
d – A dictionary to identify
- normalize_and_save(root_href: str, catalog_type: Optional[CatalogType] = None, strategy: Optional[HrefLayoutStrategy] = None, stac_io: Optional[StacIO] = None, skip_unresolved: bool = False) None [source]#
Normalizes link HREFs to the given root_href, and saves the catalog.
This is a convenience method that simply calls
Catalog.normalize_hrefs
andCatalog.save
in sequence.- Parameters
root_href – The absolute HREF that all links will be normalized against.
catalog_type – The catalog type that dictates the structure of the catalog to save. Use a member of
CatalogType
. Defaults to the root catalog.catalog_type or the current catalog catalog_type if there is no root catalog.strategy – The layout strategy to use in setting the HREFS for this catalog. If not provided, defaults to
BestPracticesLayoutStrategy
stac_io – Optional instance of
StacIO
to use. If not provided, will use the instance set while reading in the catalog, or the default instance if this is not available.skip_unresolved – Skip unresolved links when normalizing the tree. Defaults to False. Because unresolved links are not saved, this argument can be used to normalize and save only newly-added objects.
- normalize_hrefs(root_href: str, strategy: Optional[HrefLayoutStrategy] = None, skip_unresolved: bool = False) None [source]#
Normalize HREFs will regenerate all link HREFs based on an absolute root_href and the canonical catalog layout as specified in the STAC specification’s best practices.
This method mutates the entire catalog tree, unless
skip_unresolved
is True, in which case only resolved links are modified. This is useful in the case when you have loaded a large catalog and you’ve added a few items/children, and you only want to update those newly-added objects, not the whole tree.- Parameters
root_href – The absolute HREF that all links will be normalized against.
strategy – The layout strategy to use in setting the HREFS for this catalog. If not provided, defaults to
BestPracticesLayoutStrategy
skip_unresolved – Skip unresolved links when normalizing the tree. Defaults to False.
- See:
STAC best practices document for the canonical layout of a STAC.
- remove_child(child_id: str) None [source]#
Removes an child from this catalog.
- Parameters
child_id – The ID of the child to remove.
- remove_item(item_id: str) None [source]#
Removes an item from this catalog.
- Parameters
item_id – The ID of the item to remove.
- save(catalog_type: Optional[CatalogType] = None, dest_href: Optional[str] = None, stac_io: Optional[StacIO] = None) None [source]#
Save this catalog and all it’s children/item to files determined by the object’s self link HREF or a specified path.
- Parameters
catalog_type – The catalog type that dictates the structure of the catalog to save. Use a member of
CatalogType
. If not supplied, the catalog_type of this catalog will be used. If that attribute is not set, an exception will be raised.dest_href – The location where the catalog is to be saved. If not supplied, the catalog’s self link HREF is used to determine the location of the catalog file and children’s files.
stac_io – Optional instance of
StacIO
to use. If not provided, will use the instance set while reading in the catalog, or the default instance if this is not available.
Note
If the catalog type is
CatalogType.ABSOLUTE_PUBLISHED
, all self links will be included, and hierarchical links be absolute URLs. If the catalog type isCatalogType.RELATIVE_PUBLISHED
, this catalog’s self link will be included, but no child catalog will have self links, and hierarchical links will be relative URLs If the catalog type isCatalogType.SELF_CONTAINED
, no self links will be included and hierarchical links will be relative URLs.
- set_root(root: Optional[Catalog]) None [source]#
Sets the root
Catalog
orCollection
for this object.- Parameters
root – The root object to set. Passing in None will clear the root.
- to_dict(include_self_link: bool = True, transform_hrefs: bool = True) Dict[str, Any] [source]#
Generate a dictionary representing the JSON of this serialized object.
- Parameters
include_self_link – If True, the dict will contain a self link to this object. If False, the self link will be omitted.
transform_hrefs – If True, transform the HREF of hierarchical links based on the type of catalog this object belongs to (if any). I.e. if this object belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, hierarchical link HREFs will be transformed to be relative to the catalog root.
dict – A serialization of the object that can be written out as JSON.
- validate_all() None [source]#
Validates each catalog, collection contained within this catalog.
Walks through the children and items of the catalog and validates each stac object.
- Raises
STACValidationError – Raises this error on any item that is invalid. Will raise on the first invalid stac object encountered.
- walk() Iterable[Tuple['Catalog', Iterable['Catalog'], Iterable[Item]]] [source]#
Walks through children and items of catalogs.
For each catalog in the STAC’s tree rooted at this catalog (including this catalog itself), it yields a 3-tuple (root, subcatalogs, items). The root in that 3-tuple refers to the current catalog being walked, the subcatalogs are any catalogs or collections for which the root is a parent, and items represents any items that have the root as a parent.
This has similar functionality to Python’s
os.walk()
.
CatalogType#
- class pystac.CatalogType(value)[source]#
An enumeration.
- ABSOLUTE_PUBLISHED = 'ABSOLUTE_PUBLISHED'#
Absolute Published Catalog is a catalog that uses absolute links for everything, both in the links objects and in the asset hrefs.
- RELATIVE_PUBLISHED = 'RELATIVE_PUBLISHED'#
Relative Published Catalog is a catalog that uses relative links for everything, but includes an absolute self link at the root catalog, to identify its online location.
- SELF_CONTAINED = 'SELF_CONTAINED'#
A ‘self-contained catalog’ is one that is designed for portability. Users may want to download an online catalog from and be able to use it on their local computer, so all links need to be relative.
- classmethod determine_type(stac_json: Dict[str, Any]) Optional[CatalogType] [source]#
Determines the catalog type based on a STAC JSON dict.
Only applies to Catalogs or Collections
- Parameters
stac_json – The STAC JSON dict to determine the catalog type
- Returns
The catalog type of the catalog or collection. Will return None if it cannot be determined.
- Return type
Optional[CatalogType]
Collection#
- class pystac.Collection(id: str, description: str, extent: Extent, title: Optional[str] = None, stac_extensions: Optional[List[str]] = None, href: Optional[str] = None, extra_fields: Optional[Dict[str, Any]] = None, catalog_type: Optional[CatalogType] = None, license: str = 'proprietary', keywords: Optional[List[str]] = None, providers: Optional[List[Provider]] = None, summaries: Optional[Summaries] = None, assets: Optional[Dict[str, Asset]] = None)[source]#
Bases:
Catalog
A Collection extends the Catalog spec with additional metadata that helps enable discovery.
- Parameters
id – Identifier for the collection. Must be unique within the STAC.
description –
Detailed multi-line description to fully explain the collection. CommonMark 0.29 syntax MAY be used for rich text representation.
extent – Spatial and temporal extents that describe the bounds of all items contained within this Collection.
title – Optional short descriptive one-line title for the collection.
stac_extensions – Optional list of extensions the Collection implements.
href – Optional HREF for this collection, which be set as the collection’s self link’s HREF.
catalog_type – Optional catalog type for this catalog. Must be one of the values in :class`~pystac.CatalogType`.
license – Collection’s license(s) as a SPDX License identifier, various, or proprietary. If collection includes data with multiple different licenses, use various and add a link for each. Defaults to ‘proprietary’.
keywords – Optional list of keywords describing the collection.
providers – Optional list of providers of this Collection.
summaries – An optional map of property summaries, either a set of values or statistics such as a range.
extra_fields – Extra fields that are part of the top-level JSON properties of the Collection.
assets – A dictionary mapping string keys to
Asset
objects. AllAsset
values in the dictionary will have theirowner
attribute set to the created Collection.
- DEFAULT_FILE_NAME = 'collection.json'#
Default file name that will be given to this STAC object in a canonical format.
- STAC_OBJECT_TYPE: STACObjectType = 'Collection'#
- add_asset(key: str, asset: Asset) None [source]#
Adds an Asset to this item.
- Parameters
key – The unique key of this asset.
asset – The Asset to add.
- add_item(item: Item, title: Optional[str] = None, strategy: Optional[HrefLayoutStrategy] = None) None [source]#
Adds a link to an
Item
. This method will set the item’s parent to this object, and its root to this Catalog’s root.- Parameters
item – The item to add.
title – Optional title to give to the
Link
strategy – The layout strategy to use for setting the self href of the item. If not provided, defaults to
BestPracticesLayoutStrategy
.
- catalog_type: CatalogType#
The catalog type. Defaults to
CatalogType.ABSOLUTE_PUBLISHED
.
- clone() Collection [source]#
Clones this object.
Cloning an object will make a copy of all properties and links of the object; however, it will not make copies of the targets of links (i.e. it is not a deep copy). To copy a STACObject fully, with all linked elements also copied, use
STACObject.full_copy
.- Returns
The clone of this object.
- Return type
- extent: Extent#
Spatial and temporal extents that describe the bounds of all items contained within this Collection.
- extra_fields: Dict[str, Any]#
Extra fields that are part of the top-level JSON properties of the Collection.
- classmethod from_dict(d: Dict[str, Any], href: Optional[str] = None, root: Optional[Catalog] = None, migrate: bool = False, preserve_dict: bool = True) C [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
- classmethod from_file(href: str, stac_io: Optional[StacIO] = None) C [source]#
Reads a STACObject implementation from a file.
- Parameters
href – The HREF to read the object from.
stac_io – Optional instance of StacIO to use. If not provided, will use the default instance.
- Returns
The specific STACObject implementation class that is represented by the JSON read from the file located at HREF.
- full_copy(root: Optional[Catalog] = None, parent: Optional[Catalog] = None) Collection [source]#
Create a full copy of this STAC object and any stac objects linked to by this object.
- Parameters
root – Optional root to set as the root of the copied object, and any other copies that are contained by this object.
parent – Optional parent to set as the parent of the copy of this object.
- Returns
A full copy of this object, as well as any objects this object links to.
- Return type
- get_assets(media_type: Optional[Union[str, MediaType]] = None, role: Optional[str] = None) Dict[str, Asset] [source]#
Get this collection’s assets.
- Parameters
media_type – If set, filter the assets such that only those with a matching
media_type
are returned.role – If set, filter the assets such that only those with a matching
role
are returned.
- Returns
A dictionary of assets that match
media_type
and/orrole
if set or else all of this collection’s assets.- Return type
- classmethod matches_object_type(d: Dict[str, Any]) bool [source]#
Returns a boolean indicating whether the given dictionary represents a valid instance of this
STACObject
sub-class.- Parameters
d – A dictionary to identify
- summaries: Summaries#
A map of property summaries, either a set of values or statistics such as a range.
- to_dict(include_self_link: bool = True, transform_hrefs: bool = True) Dict[str, Any] [source]#
Generate a dictionary representing the JSON of this serialized object.
- Parameters
include_self_link – If True, the dict will contain a self link to this object. If False, the self link will be omitted.
transform_hrefs – If True, transform the HREF of hierarchical links based on the type of catalog this object belongs to (if any). I.e. if this object belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, hierarchical link HREFs will be transformed to be relative to the catalog root.
dict – A serialization of the object that can be written out as JSON.
Extent#
- class pystac.Extent(spatial: SpatialExtent, temporal: TemporalExtent, extra_fields: Optional[Dict[str, Any]] = None)[source]#
Describes the spatiotemporal extents of a Collection.
- Parameters
spatial – Potential spatial extent covered by the collection.
temporal – Potential temporal extent covered by the collection.
extra_fields – Dictionary containing additional top-level fields defined on the Extent object.
- extra_fields: Dict[str, Any]#
Dictionary containing additional top-level fields defined on the Extent object.
- static from_dict(d: Dict[str, Any]) Extent [source]#
Constructs an Extent from a dict.
- Returns
The Extent deserialized from the JSON dict.
- Return type
- static from_items(items: Iterable[Item], extra_fields: Optional[Dict[str, Any]] = None) Extent [source]#
Create an Extent based on the datetimes and bboxes of a list of items.
- Parameters
items – A list of items to derive the extent from.
extra_fields – Optional dictionary containing additional top-level fields defined on the Extent object.
- Returns
An Extent that spatially and temporally covers all of the given items.
- Return type
- spatial: SpatialExtent#
Potential spatial extent covered by the collection.
- temporal: TemporalExtent#
Potential temporal extent covered by the collection.
SpatialExtent#
- class pystac.SpatialExtent(bboxes: Union[List[List[float]], List[float]], extra_fields: Optional[Dict[str, Any]] = None)[source]#
Describes the spatial extent of a Collection.
- Parameters
bboxes – A list of bboxes that represent the spatial extent of the collection. Each bbox can be 2D or 3D. The length of the bbox array must be 2*n where n is the number of dimensions. For example, a 2D Collection with only one bbox would be [[xmin, ymin, xmax, ymax]]
extra_fields – Dictionary containing additional top-level fields defined on the Spatial Extent object.
- bboxes: List[List[float]]#
A list of bboxes that represent the spatial extent of the collection. Each bbox can be 2D or 3D. The length of the bbox array must be 2*n where n is the number of dimensions. For example, a 2D Collection with only one bbox would be [[xmin, ymin, xmax, ymax]]
- clone() SpatialExtent [source]#
Clones this object.
- Returns
The clone of this object.
- Return type
- extra_fields: Dict[str, Any]#
Dictionary containing additional top-level fields defined on the Spatial Extent object.
- static from_coordinates(coordinates: List[Any], extra_fields: Optional[Dict[str, Any]] = None) SpatialExtent [source]#
Constructs a SpatialExtent from a set of coordinates.
This method will only produce a single bbox that covers all points in the coordinate set.
- Parameters
coordinates – Coordinates to derive the bbox from.
extra_fields – Dictionary containing additional top-level fields defined on the SpatialExtent object.
- Returns
A SpatialExtent with a single bbox that covers the given coordinates.
- Return type
TemporalExtent#
- class pystac.TemporalExtent(intervals: Union[List[List[datetime]], List[List[Optional[datetime]]]], extra_fields: Optional[Dict[str, Any]] = None)[source]#
Describes the temporal extent of a Collection.
- Parameters
intervals – A list of two datetimes wrapped in a list, representing the temporal extent of a Collection. Open date ranges are supported by setting either the start (the first element of the interval) or the end (the second element of the interval) to None.
extra_fields – Dictionary containing additional top-level fields defined on the Temporal Extent object.
Note
Datetimes are required to be in UTC.
- clone() TemporalExtent [source]#
Clones this object.
- Returns
The clone of this object.
- Return type
- extra_fields: Dict[str, Any]#
Dictionary containing additional top-level fields defined on the Temporal Extent object.
- static from_dict(d: Dict[str, Any]) TemporalExtent [source]#
Constructs an TemporalExtent from a dict.
- Returns
The TemporalExtent deserialized from the JSON dict.
- Return type
- static from_now() TemporalExtent [source]#
Constructs an TemporalExtent with a single open interval that has the start time as the current time.
- Returns
The resulting TemporalExtent.
- Return type
- intervals: Union[List[List[datetime]], List[List[Optional[datetime]]]]#
A list of two datetimes wrapped in a list, representing the temporal extent of a Collection. Open date ranges are represented by either the start (the first element of the interval) or the end (the second element of the interval) being None.
ProviderRole#
Provider#
- class pystac.Provider(name: str, description: Optional[str] = None, roles: Optional[List[ProviderRole]] = None, url: Optional[str] = None, extra_fields: Optional[Dict[str, Any]] = None)[source]#
Provides information about a provider of STAC data. A provider is any of the organizations that captured or processed the content of the collection and therefore influenced the data offered by this collection. May also include information about the final storage provider hosting the data.
- Parameters
name – The name of the organization or the individual.
description – Optional multi-line description to add further provider information such as processing details for processors and producers, hosting details for hosts or basic contact information.
roles – Optional roles of the provider. Any of licensor, producer, processor or host.
url – Optional homepage on which the provider describes the dataset and publishes contact information.
extra_fields – Optional dictionary containing additional top-level fields defined on the Provider object.
- description: Optional[str]#
Optional multi-line description to add further provider information such as processing details for processors and producers, hosting details for hosts or basic contact information.
- extra_fields: Dict[str, Any]#
Dictionary containing additional top-level fields defined on the Provider object.
- static from_dict(d: Dict[str, Any]) Provider [source]#
Constructs an Provider from a dict.
- Returns
The Provider deserialized from the JSON dict.
- Return type
- roles: Optional[List[ProviderRole]]#
Optional roles of the provider. Any of licensor, producer, processor or host.
Summaries#
Item#
- class pystac.Item(id: str, geometry: Optional[Dict[str, Any]], bbox: Optional[List[float]], datetime: Optional[Datetime], properties: Dict[str, Any], start_datetime: Optional[Datetime] = None, end_datetime: Optional[Datetime] = None, stac_extensions: Optional[List[str]] = None, href: Optional[str] = None, collection: Optional[Union[str, Collection]] = None, extra_fields: Optional[Dict[str, Any]] = None, assets: Optional[Dict[str, Asset]] = None)[source]#
Bases:
STACObject
An Item is the core granular entity in a STAC, containing the core metadata that enables any client to search or crawl online catalogs of spatial ‘assets’ - satellite imagery, derived data, DEM’s, etc.
- Parameters
id – Provider identifier. Must be unique within the STAC.
geometry – Defines the full footprint of the asset represented by this item, formatted according to RFC 7946, section 3.1 (GeoJSON).
bbox – Bounding Box of the asset represented by this item using either 2D or 3D geometries. The length of the array must be 2*n where n is the number of dimensions. Could also be None in the case of a null geometry.
datetime – datetime associated with this item. If None, a start_datetime and end_datetime must be supplied.
properties – A dictionary of additional metadata for the item.
start_datetime – Optional start datetime, part of common metadata. This value will override any start_datetime key in properties.
end_datetime – Optional end datetime, part of common metadata. This value will override any end_datetime key in properties.
stac_extensions – Optional list of extensions the Item implements.
href – Optional HREF for this item, which be set as the item’s self link’s HREF.
collection – The Collection or Collection ID that this item belongs to.
extra_fields – Extra fields that are part of the top-level JSON properties of the Item.
assets – A dictionary mapping string keys to
Asset
objects. AllAsset
values in the dictionary will have theirowner
attribute set to the created Item.
- STAC_OBJECT_TYPE: STACObjectType = 'Feature'#
- add_asset(key: str, asset: Asset) None [source]#
Adds an Asset to this item.
- Parameters
key – The unique key of this asset.
asset – The Asset to add.
- bbox: Optional[List[float]]#
Bounding Box of the asset represented by this item using either 2D or 3D geometries. The length of the array is 2*n where n is the number of dimensions. Could also be None in the case of a null geometry.
- clone() Item [source]#
Clones this object.
Cloning an object will make a copy of all properties and links of the object; however, it will not make copies of the targets of links (i.e. it is not a deep copy). To copy a STACObject fully, with all linked elements also copied, use
STACObject.full_copy
.- Returns
The clone of this object.
- Return type
- collection: Optional[Collection]#
Collection
to which this Item belongs, if any.
- property common_metadata: CommonMetadata#
Access the item’s common metadata fields as a
CommonMetadata
object.
- datetime: Optional[Datetime]#
Datetime associated with this item. If
None
, thenstart_datetime
andend_datetime
incommon_metadata
will supply the datetime range of the Item.
- classmethod from_dict(d: Dict[str, Any], href: Optional[str] = None, root: Optional[Catalog] = None, migrate: bool = False, preserve_dict: bool = True) T [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
- classmethod from_file(href: str, stac_io: Optional[StacIO] = None) T [source]#
Reads a STACObject implementation from a file.
- Parameters
href – The HREF to read the object from.
stac_io – Optional instance of StacIO to use. If not provided, will use the default instance.
- Returns
The specific STACObject implementation class that is represented by the JSON read from the file located at HREF.
- full_copy(root: Optional[Catalog] = None, parent: Optional[Catalog] = None) Item [source]#
Create a full copy of this STAC object and any stac objects linked to by this object.
- Parameters
root – Optional root to set as the root of the copied object, and any other copies that are contained by this object.
parent – Optional parent to set as the parent of the copy of this object.
- Returns
A full copy of this object, as well as any objects this object links to.
- Return type
- geometry: Optional[Dict[str, Any]]#
Defines the full footprint of the asset represented by this item, formatted according to RFC 7946, section 3.1 (GeoJSON).
- get_assets(media_type: Optional[Union[str, MediaType]] = None, role: Optional[str] = None) Dict[str, Asset] [source]#
Get this item’s assets.
- Parameters
media_type – If set, filter the assets such that only those with a matching
media_type
are returned.role – If set, filter the assets such that only those with a matching
role
are returned.
- Returns
- A dictionary of assets that match
media_type
and/or
role
if set or else all of this item’s assets.
- A dictionary of assets that match
- Return type
- get_collection() Optional[Collection] [source]#
Gets the collection of this item, if one exists.
- Returns
If this item belongs to a collection, returns a reference to the collection. Otherwise returns None.
- Return type
Collection or None
- get_datetime(asset: Optional[Asset] = None) Optional[Datetime] [source]#
Gets an Item or an Asset datetime.
If an Asset is supplied and the Item property exists on the Asset, returns the Asset’s value. Otherwise returns the Item’s value.
- Returns
datetime or None
- make_asset_hrefs_absolute() Item [source]#
Modify each asset’s HREF to be absolute.
Any asset HREFs that are relative will be modified to absolute based on this item’s self HREF.
- Returns
self
- Return type
- make_asset_hrefs_relative() Item [source]#
Modify each asset’s HREF to be relative to this item’s self HREF.
- Returns
self
- Return type
- classmethod matches_object_type(d: Dict[str, Any]) bool [source]#
Returns a boolean indicating whether the given dictionary represents a valid instance of this
STACObject
sub-class.- Parameters
d – A dictionary to identify
- set_collection(collection: Optional[Collection]) Item [source]#
Set the collection of this item.
This method will replace any existing Collection link and attribute for this item.
- Parameters
collection – The collection to set as this item’s collection. If None, will clear the collection.
- Returns
self
- Return type
- set_datetime(datetime: Datetime, asset: Optional[Asset] = None) None [source]#
Set an Item or an Asset datetime.
If an Asset is supplied, sets the property on the Asset. Otherwise sets the Item’s value.
- set_self_href(href: Optional[str]) None [source]#
Sets the absolute HREF that is represented by the
rel == 'self'
Link
.Changing the self HREF of the item will ensure that all asset HREFs remain valid. If asset HREFs are relative, the HREFs will change to point to the same location based on the new item self HREF, either by making them relative to the new location or making them absolute links if the new location does not share the same protocol as the old location.
- Parameters
href – The absolute HREF of this object. If the given HREF is not absolute, it will be transformed to an absolute HREF based on the current working directory. If this is None the call will clear the self HREF link.
- to_dict(include_self_link: bool = True, transform_hrefs: bool = True) Dict[str, Any] [source]#
Generate a dictionary representing the JSON of this serialized object.
- Parameters
include_self_link – If True, the dict will contain a self link to this object. If False, the self link will be omitted.
transform_hrefs – If True, transform the HREF of hierarchical links based on the type of catalog this object belongs to (if any). I.e. if this object belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, hierarchical link HREFs will be transformed to be relative to the catalog root.
dict – A serialization of the object that can be written out as JSON.
Asset#
- class pystac.Asset(href: str, title: Optional[str] = None, description: Optional[str] = None, media_type: Optional[str] = None, roles: Optional[List[str]] = None, extra_fields: Optional[Dict[str, Any]] = None)[source]#
An object that contains a link to data associated with an Item or Collection that can be downloaded or streamed.
- Parameters
href – Link to the asset object. Relative and absolute links are both allowed.
title – Optional displayed title for clients and users.
description – A description of the Asset providing additional details, such as how it was processed or created. CommonMark 0.29 syntax MAY be used for rich text representation.
media_type – Optional description of the media type. Registered Media Types are preferred. See
MediaType
for common media types.roles – Optional, Semantic roles (i.e. thumbnail, overview, data, metadata) of the asset.
extra_fields – Optional, additional fields for this asset. This is used by extensions as a way to serialize and deserialize properties on asset object JSON.
- clone() Asset [source]#
Clones this asset. Makes a
deepcopy
of theextra_fields
.- Returns
The clone of this asset.
- Return type
- property common_metadata: CommonMetadata#
Access the asset’s common metadata fields as a
CommonMetadata
object.
- description: Optional[str]#
A description of the Asset providing additional details, such as how it was processed or created. CommonMark 0.29 syntax MAY be used for rich text representation.
- extra_fields: Dict[str, Any]#
Optional, additional fields for this asset. This is used by extensions as a way to serialize and deserialize properties on asset object JSON.
- classmethod from_dict(d: Dict[str, Any]) A [source]#
Constructs an Asset from a dict.
- Returns
The Asset deserialized from the JSON dict.
- Return type
- get_absolute_href() Optional[str] [source]#
Gets the absolute href for this asset, if possible.
- If this Asset has no associated Item, and the asset HREF is a relative path,
this method will return
None
. If the Item that owns the Asset has no self HREF, this will also returnNone
.
- Returns
- The absolute HREF of this asset, or None if an absolute HREF could not
be determined.
- Return type
- has_role(role: str) bool [source]#
Check if a role exists in the Asset role list.
- Parameters
role – Role to check for existence.
- Returns
True if role exists, else False.
- Return type
- media_type: Optional[str]#
Optional description of the media type. Registered Media Types are preferred. See
MediaType
for common media types.
- owner: Optional[Union[Item, Collection]]#
The
Item
orCollection
that this asset belongs to, orNone
if it has no owner.
- roles: Optional[List[str]]#
Optional, Semantic roles (i.e. thumbnail, overview, data, metadata) of the asset.
- set_owner(obj: Union[Collection, Item]) None [source]#
Sets the owning item of this Asset.
The owning item will be used to resolve relative HREFs of this asset.
- Parameters
obj – The Collection or Item that owns this asset.
CommonMetadata#
- class pystac.CommonMetadata(object: Union[Asset, Item])[source]#
Object containing fields that are not included in core item schema but are still commonly used. All attributes are defined within the properties of this item and are optional
- Parameters
properties – Dictionary of attributes that is the Item’s properties
- property constellation: Optional[str]#
Gets or set the name of the constellation associate with an object.
ItemCollection#
- class pystac.ItemCollection(items: Iterable[Union[Item, Dict[str, Any]]], extra_fields: Optional[Dict[str, Any]] = None, clone_items: bool = True)[source]#
Bases:
Collection
[Item
]Implementation of a GeoJSON FeatureCollection whose features are all STAC Items.
All
Item
instances passed to theItemCollection
instance during instantiation are cloned and have their"root"
URL cleared. Instances of this class implement the abstract methods oftyping.Collection
and can also be added together (see below for examples using these methods).Any additional top-level fields in the FeatureCollection are retained in
extra_fields
by thefrom_dict()
andfrom_file()
methods and will be present in the serialized file fromsave_object()
.- Parameters
items – List of
Item
instances to include in theItemCollection
.extra_fields – Dictionary of additional top-level fields included in the
ItemCollection
.clone_items – Optional flag indicating whether
Item
instances should be cloned before storing in theItemCollection
. Setting toFalse
will result in faster instantiation, but changes made toItem
instances in theItemCollection
will mutate the originalItem
. Defaults toTrue
.
Examples
Loop over all items in the :class`~ItemCollection`
>>> item_collection: ItemCollection = ... >>> for item in item_collection: ... ...
Get the number of
Item
instances in theItemCollection
>>> length: int = len(item_collection)
Check if an
Item
is in theItemCollection
. Note that theclone_items
argument must beFalse
for this to returnTrue
, since equality of PySTAC objects is currently evaluated using default object equality (i.e.item_1 is item_2
).>>> item: Item = ... >>> item_collection = ItemCollection(items=[item], clone_items=False) >>> assert item in item_collection
Combine
ItemCollection
instances>>> item_1: Item = ... >>> item_2: Item = ... >>> item_3: Item = ... >>> item_collection_1 = ItemCollection(items=[item_1, item_2]) >>> item_collection_2 = ItemCollection(items=[item_2, item_3]) >>> combined = item_collection_1 + item_collection_2 >>> assert len(combined) == 4 # If an item is present in both ItemCollections it will occur twice
- clone() ItemCollection [source]#
Creates a clone of this instance. This clone is a deep copy; all
Item
instances are cloned and all additional top-level fields are deep copied.
- extra_fields: Dict[str, Any]#
Dictionary of additional top-level fields for the GeoJSON FeatureCollection.
- classmethod from_dict(d: Dict[str, Any], preserve_dict: bool = True, root: Optional[Catalog] = None) C [source]#
Creates a
ItemCollection
instance from a dictionary.- Parameters
d – The dictionary from which the
ItemCollection
will be createdpreserve_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.
- classmethod from_file(href: str, stac_io: Optional[StacIO] = None) C [source]#
Reads a
ItemCollection
from a JSON file.- Parameters
href – Path to the file.
stac_io – A
StacIO
instance to use for file I/O
- static is_item_collection(d: Dict[str, Any]) bool [source]#
Checks if the given dictionary represents a valid
ItemCollection
.- Parameters
d – Dictionary to check
- items: List[Item]#
List of
pystac.Item
instances contained in thisItemCollection
.
- save_object(dest_href: str, stac_io: Optional[StacIO] = None) None [source]#
Saves this instance to the
dest_href
location.- Parameters
dest_href – Location to which the file will be saved.
stac_io – Optional
StacIO
instance to use. If not provided, will use the default instance.
- to_dict(transform_hrefs: bool = False) Dict[str, Any] [source]#
Serializes an
ItemCollection
instance to a JSON-like dictionary.- Parameters
transform_hrefs – If True, transform the HREF of hierarchical links of Items based on the type of catalog the Item belongs to (if any). I.e. if the item belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, hierarchical link HREFs will be transformed to be relative to the catalog root. This can be slow if the Items have root links that have not yet been resolved. Defaults to False.
Link#
- class pystac.Link(rel: Union[str, pystac.RelType], target: Union[str, STACObject], media_type: Optional[str] = None, title: Optional[str] = None, extra_fields: Optional[Dict[str, Any]] = None)[source]#
A link connects a
STACObject
to another entity.The target of a link can be either another STACObject, or an HREF. When serialized, links always refer to the HREF of the target. Links are lazily deserialized - this is, when you read in a link, it does not automatically load in the STACObject that is the target (if the link is pointing to a STACObject). When a user is crawling through a catalog or when additional metadata is required, PySTAC uses the
Link.resolve_stac_object
method to load in and deserialize STACObjects. This mechanism is used within the PySTAC codebase and normally does not need to be considered by the user - ideally the lazy deserialization of STACObjects is transparent to clients of PySTAC.- Parameters
rel – The relation of the link (e.g. ‘child’, ‘item’). Registered rel Types are preferred. See
RelType
for common media types.target – The target of the link. If the link is unresolved, or the link is to something that is not a STACObject, the target is an HREF. If resolved, the target is a STACObject.
media_type – Optional description of the media type. Registered Media Types are preferred. See
MediaType
for common media types.title – Optional title for this link.
extra_fields – Optional, additional fields for this link. This is used by extensions as a way to serialize and deserialize properties on link object JSON.
- property absolute_href: str#
Returns the absolute HREF for this link.
If the href is None, this will throw an exception. Use get_absolute_href if there may not be an href set.
- classmethod canonical(item_or_collection: Union[Item, Collection], title: Optional[str] = None) L [source]#
Creates a canonical link to an Item or Collection.
- classmethod child(c: Catalog, title: Optional[str] = None) L [source]#
Creates a link to a child Catalog or Collection.
- clone() Link [source]#
Clones this link.
This makes a copy of all link information, but does not clone a STACObject if one is the target of this link.
- Returns
The cloned link.
- Return type
- classmethod collection(c: Collection) L [source]#
Creates a link to an item’s Collection.
- extra_fields: Dict[str, Any]#
Optional, additional fields for this link. This is used by extensions as a way to serialize and deserialize properties on link object JSON.
- classmethod from_dict(d: Dict[str, Any]) L [source]#
Deserializes a Link from a dict.
- Parameters
d – The dict that represents the Link in JSON
- Returns
Link instance constructed from the dict.
- Return type
- get_absolute_href() Optional[str] [source]#
Gets the absolute href for this link, if possible.
- Returns
Returns this link’s HREF. It attempts to derive an absolute HREF from this link; however, if the link is relative, has no owner, and has an unresolved target, this will return a relative HREF.
- Return type
- get_href(transform_href: bool = True) Optional[str] [source]#
Gets the HREF for this link.
- Parameters
transform_href – If True, transform the HREF based on the type of catalog the owner belongs to (if any). I.e. if the link owner belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, the HREF will be transformed to be relative to the catalog root if this is a hierarchical link relation.
- Returns
Returns this link’s HREF. If there is an owner of the link and the root catalog (if there is one) is of type RELATIVE_PUBLISHED, then the HREF returned will be relative. In all other cases, this method will return an absolute HREF.
- Return type
- get_target_str() Optional[str] [source]#
Returns this link’s target as a string.
If a string href was provided, returns that. If not, tries to resolve the self link of the target object.
- has_target_href() bool [source]#
Returns true if this link has a string href in its target information.
- property href: str#
Returns the HREF for this link.
If the href is None, this will throw an exception. Use get_href if there may not be an href.
- is_hierarchical() bool [source]#
Returns true if this link’s rel type is hierarchical.
Hierarchical links are used to build relationships in STAC, e.g. “parent”, “child”, “item”, etc. For a complete list of hierarchical relation types, see
HIERARCHICAL_LINKS
.- Returns
True if the link’s rel type is hierarchical.
- Return type
- is_resolved() bool [source]#
Determines if the link’s target is a resolved STACObject.
- Returns
True if this link is resolved.
- Return type
- media_type: Optional[str]#
Optional description of the media type. Registered Media Types are preferred. See
MediaType
for common media types.
- owner: Optional[STACObject]#
The owner of this link. The link will use its owner’s root catalog
ResolvedObjectCache
to resolve objects, and will create absolute HREFs from relative HREFs against the owner’s self HREF.
- rel: Union[str, pystac.RelType]#
The relation of the link (e.g. ‘child’, ‘item’). Registered rel Types are preferred. See
RelType
for common media types.
- resolve_stac_object(root: Optional[Catalog] = None) Link [source]#
Resolves a STAC object from the HREF of this link, if the link is not already resolved.
- Parameters
root – Optional root of the catalog for this link. If provided, the root’s resolved object cache is used to search for previously resolved instances of the STAC object.
- classmethod self_href(href: Union[str, PathLike]) L [source]#
Creates a self link to a file’s location.
- set_owner(owner: Optional[STACObject]) Link [source]#
Sets the owner of this link.
- Parameters
owner – The owner of this link. Pass None to clear.
- property target: Union[str, STACObject]#
The target of the link. If the link is unresolved, or the link is to something that is not a STACObject, the target is an HREF. If resolved, the target is a STACObject.
- property title: Optional[str]#
Optional title for this link. If not provided during instantiation, this will attempt to get the title from the STAC object that the link references.
- to_dict(transform_href: bool = True) Dict[str, Any] [source]#
Generate a dictionary representing the JSON of this serialized Link.
- Parameters
transform_href – If
True
, transform the HREF based on the type of catalog the owner belongs to (if any). I.e. if the link owner belongs to a root catalog that is RELATIVE_PUBLISHED or SELF_CONTAINED, the HREF will be transformed to be relative to the catalog root if this is a hierarchical link relation.- Returns
A serialization of the Link that can be written out as JSON.
- Return type
MediaType#
- class pystac.MediaType(value)[source]#
A list of common media types that can be used in STAC Asset and Link metadata.
- COG = 'image/tiff; application=geotiff; profile=cloud-optimized'#
- FLATGEOBUF = 'application/vnd.flatgeobuf'#
- GEOJSON = 'application/geo+json'#
- GEOPACKAGE = 'application/geopackage+sqlite3'#
- GEOTIFF = 'image/tiff; application=geotiff'#
- HDF = 'application/x-hdf'#
- HDF5 = 'application/x-hdf5'#
- HTML = 'text/html'#
- JPEG = 'image/jpeg'#
- JPEG2000 = 'image/jp2'#
- JSON = 'application/json'#
- PDF = 'application/pdf'#
- PNG = 'image/png'#
- TEXT = 'text/plain'#
- TIFF = 'image/tiff'#
- XML = 'application/xml'#
RelType#
- class pystac.RelType(value)[source]#
A list of common rel types that can be used in STAC Link metadata. See “Using Relation Types in the STAC Best Practices for guidelines on using relation types. You may also want to refer to the “Relation type” documentation for Catalogs, Collections, or Items for relation types specific to those STAC objects.
- ALTERNATE = 'alternate'#
- CANONICAL = 'canonical'#
- CHILD = 'child'#
- COLLECTION = 'collection'#
- DERIVED_FROM = 'derived_from'#
- ITEM = 'item'#
- ITEMS = 'items'#
- LICENSE = 'license'#
- NEXT = 'next'#
- PARENT = 'parent'#
- PREV = 'prev'#
- PREVIEW = 'preview'#
- ROOT = 'root'#
- SELF = 'self'#
- VIA = 'via'#
StacIO#
- class pystac.StacIO(headers: Optional[Dict[str, str]] = None)[source]#
-
- json_dumps(json_dict: Dict[str, Any], *args: Any, **kwargs: Any) str [source]#
Method used internally by
StacIO
instances to serialize a dictionary to a JSON string.This method may be overwritten in
StacIO
sub-classes to provide custom serialization logic. The method accepts arbitrary keyword arguments. These are not used by the default implementation, but may be used by sub-class implementations.- Parameters
json_dict – The dictionary to serialize
- json_loads(txt: str, *args: Any, **kwargs: Any) Dict[str, Any] [source]#
Method used internally by
StacIO
instances to deserialize a dictionary from a JSON string.This method may be overwritten in
StacIO
sub-classes to provide custom deserialization logic. The method accepts arbitrary keyword arguments. These are not used by the default implementation, but may be used by sub-class implementations.- Parameters
txt – The JSON string to deserialize to a dictionary.
- read_json(source: Union[str, PathLike], *args: Any, **kwargs: Any) Dict[str, Any] [source]#
Read a dict from the given source.
See
StacIO.read_text
for usage of str vs Link as a parameter.- Parameters
source – The source from which to read.
*args – Additional positional arguments to be passed to
StacIO.read_text()
.**kwargs – Additional keyword arguments to be passed to
StacIO.read_text()
.
- Returns
A dict representation of the JSON contained in the file at the given source.
- Return type
- read_stac_object(source: HREF, root: Optional[Catalog] = None, *args: Any, **kwargs: Any) STACObject [source]#
Read a STACObject from a JSON file at the given source.
See
StacIO.read_text
for usage of str vs Link as a parameter.- Parameters
source – The source from which to read.
root – Optional root of the catalog for this object. If provided, the root’s resolved object cache can be used to search for previously resolved instances of the STAC object.
*args – Additional positional arguments to be passed to
StacIO.read_json()
.**kwargs – Additional keyword arguments to be passed to
StacIO.read_json()
.
- Returns
The deserialized STACObject from the serialized JSON contained in the file at the given uri.
- Return type
- abstract read_text(source: Union[str, PathLike], *args: Any, **kwargs: Any) str [source]#
Read text from the given URI.
The source to read from can be specified as a string or
os.PathLike
object (Link
is a path-like object). If it is a string, it must be a URI or local path from which to read. Using aLink
enables implementations to use additional link information, such as paging information contained in the extended links described in the STAC API spec.- Parameters
source – The source to read from.
*args – Arbitrary positional arguments that may be utilized by the concrete implementation.
**kwargs – Arbitrary keyword arguments that may be utilized by the concrete implementation.
- Returns
The text contained in the file at the location specified by the uri.
- Return type
- save_json(dest: Union[str, PathLike], json_dict: Dict[str, Any], *args: Any, **kwargs: Any) None [source]#
Write a dict to the given URI as JSON.
See
StacIO.write_text
for usage of str vs Link as a parameter.- Parameters
dest – The destination file to write the text to.
json_dict – The JSON dict to write.
*args – Additional positional arguments to be passed to
StacIO.json_dumps()
.**kwargs – Additional keyword arguments to be passed to
StacIO.json_dumps()
.
- classmethod set_default(stac_io_class: Callable[[], StacIO]) None [source]#
Set the default StacIO instance to use.
- stac_object_from_dict(d: Dict[str, Any], href: Optional[HREF] = None, root: Optional[Catalog] = None, preserve_dict: bool = True) STACObject [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 parameterd
may be modified during this method call. Otherwise the dict is not mutated. Defaults toTrue
, which results results in a deepcopy of the parameter. Set toFalse
when possible to avoid the performance hit of a deepcopy.
- abstract write_text(dest: Union[str, PathLike], txt: str, *args: Any, **kwargs: Any) None [source]#
Write the given text to a file at the given URI.
The destination to write to can be specified as a string or
os.PathLike
object (Link
is a path-like object). If it is a string, it must be a URI or local path from which to read. Using aLink
enables implementations to use additional link information.- Parameters
dest – The destination to write to.
txt – The text to write.
Errors#
STACError#
STACTypeError#
DuplicateObjectKeyError#
ExtensionAlreadyExistsError#
ExtensionTypeError#
ExtensionNotImplemented#
RequiredPropertyMissing#
- class pystac.RequiredPropertyMissing(obj: Union[str, Any], prop: str, msg: Optional[str] = None)[source]#
This error is raised when a required value was expected to be there but was missing or None. This will happen, for example, in an extension that has required properties, where the required property is missing from the extended object
- Parameters
obj – Description of the object that will have a property missing. Should include a __repr__ that identifies the object for the error message, or be a string that describes the object.
prop – The property that is missing
STACValidationError#
- class pystac.STACValidationError(message: str, source: Optional[Any] = None)[source]#
Represents a validation error. Thrown by validation calls if the STAC JSON is invalid.
- Parameters
source – Source of the exception. Type will be determined by the validation implementation. For the default JsonSchemaValidator this will a the
jsonschema.ValidationError
.