Reference¶
The public and stable API functions, classes and exceptions are all provided by the planet.api namespace.
The Client Object¶
The Client class is the supported way to access the API.
Unless specific functionality is needed, the correct way to instantiate a Client is with zero arguments.
The Client will resolve the API_KEY from the operating system environment using the PL_API_KEY value.
client = api.ClientV1()
- class planet.api.ClientV1¶
ClientV1 provides basic low-level access to Planet’s API. Only one ClientV1 should be in existence for an application. The Client is thread safe and takes care to avoid API throttling and also retry any throttled requests. Most functions take JSON-like dict representations of API request bodies. Return values are usually a subclass of
planet.api.models.Body
. Any exceptional http responses are handled by translation to one of theplanet.api.exceptions
classes.- activate(asset)¶
Request activation of the specified asset representation.
Asset representations are obtained from
get_assets()
.- Parameters
dict (request) – An asset representation from the API.
- Returns
planet.api.models.Body
with no response content- Raises
planet.api.exceptions.APIException – On API error.
- cancel_order(order_id)¶
Cancel a running order by Order ID.
- Parameters
str (order_id) – The ID of the Order to cancel
- Returns
planet.api.models.Order
- Raises
planet.api.exceptions.APIException – On API error.
- check_analytics_connection()¶
Validate that we can use the Analytics API. Useful to test connectivity to test environments. :returns:
planet.api.models.JSON
- create_order(request)¶
Create an order.
- Parameters
asset –
- Returns
planet.api.models.Response
containing aplanet.api.models.Body
of the asset.- Raises
planet.api.exceptions.APIException – On API error.
- create_search(request)¶
Create a new saved search from the specified request. The request must contain a
name
property.- Parameters
request – see Client Search Requests
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- download(asset, callback=None)¶
Download the specified asset. If provided, the callback will be invoked asynchronously. Otherwise it is up to the caller to handle the response Body.
- Parameters
dict (asset) – An asset representation from the API
callback – An optional function to aysnchronsously handle the download. See
planet.api.write_to_file()
- Returns
planet.api.models.Response
containing aplanet.api.models.Body
of the asset.- Raises
planet.api.exceptions.APIException – On API error.
- download_location(location, callback=None)¶
Download an item in an order.
- Parameters
location – location URL of item
- Returns
planet.api.models.Response
containing aplanet.api.models.Body
of the asset.- Raises
planet.api.exceptions.APIException – On API error.
- download_order(order_id, callback=None)¶
Download all items in an order.
- Parameters
order_id – ID of order to download
- Returns
planet.api.models.Response
containing aplanet.api.models.Body
of the asset.- Raises
planet.api.exceptions.APIException – On API error.
- download_quad(quad, callback=None)¶
Download the specified mosaic quad. If provided, the callback will be invoked asynchronously. Otherwise it is up to the caller to handle the response Body.
- Parameters
dict (quad) – A mosaic quad representation from the API
callback – An optional function to aysnchronsously handle the download. See
planet.api.write_to_file()
- Returns
planet.api.models.Response
containing aplanet.api.models.Body
of the asset.- Raises
planet.api.exceptions.APIException – On API error.
- get_assets(item)¶
Get the assets for the provided item representations.
Item representations are obtained from search requests.
- Parameters
dict (request) – An item representation from the API.
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- get_assets_by_id(item_type, id)¶
Get an item’s asset response for the given item_type and id
- Parameters
str (id) – A valid item-type
str – The id of the item
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- get_associated_resource_for_analytic_feature(subscription_id, feature_id, resource_type)¶
Get resource associated with some feature in an analytic subscription. Response might be JSON or a TIF, depending on requested resource. :param subscription_id str: ID of subscription :param feature_id str: ID of feature :param resource_type str: Type of resource to request. :raises planet.api.exceptions.APIException: On API error or resource type unavailable. :returns:
planet.api.models.JSON
for resource type source-image-info, but can also returnplanet.api.models.Response
containing aplanet.api.models.Body
of the resource.
- get_collection_info(subscription_id)¶
Get the information describing a specific collection. :param subscription_id: :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.JSON
- get_feed_info(feed_id)¶
Get the information describing a specific collection. :param subscription_id: :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.JSON
- get_individual_order(order_id)¶
Get order request details by Order ID.
- Parameters
str (order_id) – The ID of the Order
- Returns
planet.api.models.Order
- Raises
planet.api.exceptions.APIException – On API error.
- get_item(item_type, id)¶
Get the an item response for the given item_type and id
- Parameters
str (id) – A valid item-type
str – The id of the item
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- get_mosaic_by_name(name)¶
Get the API representation of a mosaic by name.
- Parameters
str (name) – The name of the mosaic
- Returns
planet.api.models.Mosaics
- Raises
planet.api.exceptions.APIException – On API error.
- get_mosaic_series(series_id)¶
Get information pertaining to a mosaics series :returns:
planet.api.models.JSON
- get_mosaics(name_contains=None)¶
Get information for all mosaics accessible by the current user.
- Returns
planet.api.models.Mosaics
- get_mosaics_for_series(series_id)¶
Get list of mosaics available for a series :returns:
planet.api.models.Mosaics
- get_orders()¶
Get information for all pending and completed order requests for the current user.
- Returns
planet.api.models.Orders
- get_quad_by_id(mosaic, quad_id)¶
Get a quad response for a specific mosaic and quad.
- Parameters
dict (mosaic) – A mosaic representation from the API
str (quad_id) – A quad id (typically <xcoord>-<ycoord>)
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- get_quad_contributions(quad)¶
Get information about which scenes contributed to a quad.
- Parameters
dict (quad) – A quad representation from the API
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- get_quads(mosaic, bbox=None)¶
Search for quads from a mosaic that are inside the specified bounding box. Will yield all quads if no bounding box is specified.
- Parameters
dict (mosaic) – A mosaic representation from the API
tuple (bbox) – A lon_min, lat_min, lon_max, lat_max area to search
- Returns
planet.api.models.MosaicQuads
- Raises
planet.api.exceptions.APIException – On API error.
- get_searches(quick=False, saved=True)¶
Get searches listing.
- Parameters
bool (quick) – Include quick searches (default False)
saved (quick) – Include saved searches (default True)
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- get_subscription_info(subscription_id)¶
Get the information describing a specific subscription. :param subscription_id: :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.JSON
- list_analytic_collections()¶
Get collections that the authenticated user has access to :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.WFS3Collections
- list_analytic_feeds(stats)¶
Get collections that the authenticated user has access to :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.Feeds
- list_analytic_subscriptions(feed_id)¶
Get subscriptions that the authenticated user has access to :param feed_id str: Return subscriptions associated with a particular feed only. :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.Subscriptions
- list_collection_features(subscription_id, bbox=None, time_range=None, before=None, after=None)¶
List features for an analytic subscription. :param subscription_id: :param time_range str: ISO format datetime interval. :param bbox tuple: A lon_min, lat_min, lon_max, lat_max area to search :param before str: return features published before item with given ID :param after str: return features published after item with given ID :raises planet.api.exceptions.APIException: On API error. :returns:
planet.api.models.WFS3Features
- quick_search(request, **kw)¶
Execute a quick search with the specified request.
- Parameters
request – see Client Search Requests
**kw – See Options below
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- Options
page_size (int): Size of response pages
sort (string): Sorting order in the form field (asc|desc)
- saved_search(sid, **kw)¶
Execute a saved search by search id.
- Parameters
string (sid) – The id of the search
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- Options
page_size (int): Size of response pages
sort (string): Sorting order in the form field (asc|desc)
- stats(request)¶
Get stats for the provided request.
- Parameters
dict (request) – A search request that also contains the ‘interval’ property.
- Returns
- Raises
planet.api.exceptions.APIException – On API error.
- wfs_conformance()¶
Details about WFS3 conformance :returns:
planet.api.models.JSON
Client Search Requests¶
The general search request form is a Python dict, for example.
{
"item_types": ['PSScene'],
"filter": {
"type": "AndFilter",
"config": [
"type": "RangeFilter",
"field_name": "cloud_cover",
"config": {
"lte": 0.5
}
]
}
}
The stats
function requires an additional interval
property in the
request body.
When creating a saved search, the name
property in the request body will
be used to give the new search a name.
Note
Request and Filter logic is not validated on the client.
Filters¶
The filters module provides a small convenience layer for building filters and requests.
- planet.api.filters.and_filter(*predicates)¶
Build an and filter from the provided predicate filters.
>>> filt = and_filter( ... range_filter('cloud_cover', gt=0.1), ... range_filter('cloud_cover', lt=0.2) ... ) >>> filt['type'] 'AndFilter' >>> filt['config'][0] == {'config': {'gt': 0.1}, 'field_name': 'cloud_cover', 'type': 'RangeFilter'} True >>> filt['config'][1] == {'config': {'lt': 0.2}, 'field_name': 'cloud_cover', 'type': 'RangeFilter'} True
- planet.api.filters.build_search_request(filter_like, item_types, name=None, interval=None)¶
Build a data-api search request body for the specified item_types. If ‘filter_like’ is a request, item_types will be merged and, if name or interval is provided, will replace any existing values.
- Parameters
filter_like (dict) – a filter or request with a filter
item_types (sequence(str)) – item-types to specify in the request
name (str) – optional name
interval (str) – optional interval [year, month, week, day]
- planet.api.filters.date_range(field_name, **kwargs)¶
Build a DateRangeFilter.
Predicate arguments accept a str that is ISO-8601 format or a value that has an isoformat callable that returns an ISO-8601 compliant str.
If no timezone is provided, UTC is assumed for RFC 3339 compatability.
- Raises
ValueError if predicate value does not parse
>>> date_range('acquired', gt='2017') == {'config': {'gt': '2017-01-01T00:00:00Z'}, 'field_name': 'acquired', 'type': 'DateRangeFilter'} True
- planet.api.filters.geom_filter(geom, field_name=None)¶
Build a GeometryFilter from the provided geosjon geom dict.
- Parameters
geom (geojson) – the geojson geom dict
field_name (str) – optional field name, default is ‘geometry’
- planet.api.filters.is_filter_like(filter_like)¶
Check if the provided dict looks like a search request or filter.
- planet.api.filters.num_filter(field_name, *vals)¶
Build a NumberInFilter.
>>> num_filter('value', 50, 100) == {'config': (50, 100), 'field_name': 'value', 'type': 'NumberInFilter'} True
- planet.api.filters.or_filter(*predicates)¶
Build an or filter from the provided predicate filters.
>>> import datetime >>> n = datetime.datetime(year=2017, month=2, day=14) >>> filt = or_filter( ... date_range('acquired', gt=n), ... range_filter('cloud_cover', gt=0.1), ... ) >>> filt['type'] 'OrFilter' >>> filt['config'][0] == {'config': {'gt': '2017-02-14T00:00:00Z'}, 'field_name': 'acquired', 'type': 'DateRangeFilter'} True >>> filt['config'][1] == {'config': {'gt': 0.1}, 'field_name': 'cloud_cover', 'type': 'RangeFilter'} True
- planet.api.filters.permission_filter(*perms)¶
Build a PermissionFilter with the specified permissions.
>>> permission_filter('assets:download') == {'type': 'PermissionFilter', 'config': ('assets:download',)} True
- planet.api.filters.range_filter(field_name, **kwargs)¶
Build a RangeFilter.
>>> range_filter('cloud_cover', gt=0.1) == {'config': {'gt': 0.1}, 'field_name': 'cloud_cover', 'type': 'RangeFilter'} True
- planet.api.filters.string_filter(field_name, *vals)¶
Build a StringInFilter.
>>> string_filter('id', 'id1', 'id2', 'id3') == {'config': ('id1', 'id2', 'id3'), 'field_name': 'id', 'type': 'StringInFilter'} True
Client Return Values¶
Most Client methods return a Body
subclass that provides access to the HTTP response body in addition to the HTTP request and response details.
For many responses, it is sufficient to use the get method to obtain the HTTP response as JSON.
For paginated responses, the Paged
provides convenience functions to explicitly page through results as well as an iterator to the underlying items in each response.
Download functions return a Response
object that handles some aspects of asynchronous execution. Namely, streaming chunks to a handler to prevent memory issues and awaiting completion of the task.
The basic Body methods include:
- class planet.api.models.Body¶
A Body is a representation of a resource from the API.
- get_raw()¶
Get the decoded text content from the response
- last_modified()¶
Read the last-modified header as a datetime, if present.
- property name¶
The name of this resource. The default is to use the content-disposition header value from the response.
- write(file=None, callback=None)¶
Write the contents of the body to the optionally provided file and providing progress to the optional callback. The callback will be invoked 3 different ways:
First as
callback(start=self)
For each chunk of data written as
callback(wrote=chunk_size_in_bytes, total=all_byte_cnt)
Upon completion as
callback(finish=self)
- Parameters
file – file name or file-like object
callback – optional progress callback
The Response class returned by download functions has two methods:
- class planet.api.models.Response¶
- cancel()¶
Cancel any request.
- get_body()¶
Get the response Body
- Returns Body
A Body object containing the response.
- wait()¶
Await completion of this request.
- Returns Body
A Body object containing the response.
Most responses are more specific than a body. The JSON body provides the contents as JSON.
Paginated responses provide a paging iterator as well as an iterator of each pages contents.
The Paged.items_iter()
method provides iteration over the contents of each page response.
For examples, an Items
response page contains a FeatureCollection of zero or more Item objects.
Each Item is a record represented as a GeoJSON feature with properties describing it’s metadata.
When using the iterator from the Paged.items_iter()
method, only Item Feature objects will be returned.
To handle assembling the items from each page into a collection again and streaming them as JSON, use the Paged.json_encode()
method.
- class planet.api.models.Paged¶
- items_iter(limit)¶
Get an iterator of the ‘items’ in each page. Instead of a feature collection from each page, the iterator yields the features.
- Parameters
limit (int) – The number of ‘items’ to limit to.
- Returns
iter of items in page
- iter(pages=None)¶
Get an iterator of pages.
- Parameters
pages (int) – optional limit to number of pages
- Returns
iter of this and subsequent pages
- json_encode(out, limit=None, sort_keys=False, indent=None)¶
Encode the results of this paged response as JSON writing to the provided file-like out object. This function will iteratively read as many pages as present, streaming the contents out as JSON.
- Parameters
out (file-like) – an object with a write function
limit (int) – optional maximum number of items to write
sort_keys (bool) – if True, output keys sorted, default is False
indent (bool) – if True, indent output, default is False
- class planet.api.models.Items¶
Items is a Body that contains a FeatureCollection so when using items_iter, it will yield Feature GeoJSON objects.
- class planet.api.models.Searches¶
Searches is a Body that contains an array of searches, so when using items_iter, it will yield Search JSON objects.
Utilities¶
- planet.api.write_to_file(directory=None, callback=None, overwrite=True)¶
Create a callback handler for asynchronous Body handling.
If provided, the callback will be invoked as described in
planet.api.models.Body.write()
. In addition, if the download is skipped because the destination exists, the callback will be invoked withcallback(skip=body)
.The name of the file written to will be determined from the Body.name property.
- Parameters
str (directory) – The optional directory to write to.
func (callback) – An optional callback to receive notification of write progress.
bool (overwrite) – Overwrite any existing files. Defaults to True.
Activating and Downloading Many Assets¶
A common use case is to activate and download the results of a search. While the Client provides the lower-level functionality for this, the Downloader class provides convenience for managing this process for a large number of items and assets.
Create a downloader using:
- planet.api.downloader.create(client, mosaic=False, order=False, **kw)¶
Create a Downloader with the provided client.
- Parameters
bool (mosaic) – If True, the Downloader will fetch mosaic quads.
- Returns
- class planet.api.downloader.Downloader¶
A Downloader manages activation and download of Item Assets from the Data API. A Downloader should only be processing one request to either activate or download at a time. These functions are synchronous and will return on completion. Completion of activation or download events can be tracked by changing the on_complete method of the Downloader while the stats function allows for polling of internal state.
- activate(items, asset_types)¶
Request activation of specified asset_types for the sequence of items.
- Parameters
items – a sequence of Item representations.
list (asset_types) – list of asset-type (str)
- download(items, asset_types, dest)¶
Request activation and download of specified asset_types for the sequence of items.
- Parameters
items – a sequence of Item representations.
list (asset_types) – list of asset-type (str)
str (dest) – Download destination directory, must exist.
- on_complete(item, asset, path=None)¶
Notification of processing an item’s asset, invoked on completion of activate or download.
- Parameters
item – The API representation of the item
asset – The API representation of the asset
path – If downloaded, the location of the downloaded asset, otherwise None
- shutdown()¶
Halt execution.
- stats()¶
Retrieve internal state of the Downloader.
Returns a dict of state:
paging: bool indicating that search results are being processed
activating: int number of items in the inactive or activating state
downloading: int number of items actively downloading
downloaded: string representation of MB transferred
complete: int number of completed downloads
pending: int number of items awaiting download
Client Exceptions¶
In addition to other exceptions, expected or otherwise, each HTTP operation has the potential to raise one of the following exceptions:
- exception planet.api.exceptions.APIException¶
General unexpected response
- exception planet.api.exceptions.BadQuery¶
Invalid inputs, HTTP 400
- exception planet.api.exceptions.InvalidAPIKey¶
Invalid key, HTTP 401
- exception planet.api.exceptions.InvalidIdentity¶
Raised when logging in with invalid credentials
- exception planet.api.exceptions.MissingResource¶
Request for non existing resource, HTTP 404
- exception planet.api.exceptions.NoPermission¶
Insufficient permissions, HTTP 403
- exception planet.api.exceptions.OverQuota¶
Quota exceeded, HTTP 429
- exception planet.api.exceptions.RequestCancelled¶
Internal exception when a request is cancelled
- exception planet.api.exceptions.ServerError¶
Unexpected internal server error, HTTP 500
- exception planet.api.exceptions.TooManyRequests¶
Too many requests, HTTP 429