Skip to content

Python SDK API Reference

Auth (ABC, Auth)

Handle authentication information for use with Planet APIs. Static constructor methods should be used to create an auth context that can be used by Planet API client modules to authenticate requests made to the Planet service.

async_auth_flow(self, request) inherited

Execute the authentication flow asynchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

auth_flow(self, request) inherited

Execute the authentication flow.

To dispatch a request, yield it:

yield request

The client will .send() the response back into the flow generator. You can access it like so:

response = yield request

A return (or reaching the end of the generator) will result in the client returning the last response obtained from the server.

You can dispatch as many requests as is necessary.

device_user_login_complete(self, login_initialization_info)

Complete a user login that uses the OAuth2 Device Code Flow for applications that was initiated by a call to device_user_login_initiate(). The structure that was returned from device_user_login_initiate() should be passed to this function unaltered after it has been used to prompt the user.

device_user_login_initiate(self)

Initiate a user login that uses the OAuth2 Device Code Flow for applications that cannot operate a browser locally. The returned dictionary should be used to prompt the user to complete the process, and will conform to RFC 8628.

ensure_initialized(self, allow_open_browser=False, allow_tty_prompt=False)

Do everything necessary to ensure the auth context is ready for use, while still biasing towards just-in-time operations and not making unnecessary network requests or prompts for user interaction.

This can be more complex than it sounds given the variations in possible session state. Clients may be initialized with active sessions, initialized with stale but still valid sessions, initialized with invalid or expired sessions, or completely uninitialized. The process taken to ensure client readiness with as little user disruption as possible is as follows:

  1. If the client has been logged in and has a non-expired session, the client will be considered ready without prompting the user or probing the network. This will not require user interaction.
  2. If the client has not been logged in and is an M2M client, the client will be considered ready without prompting the user or probing the network. This will not require user interaction. Login will be delayed until it is required.
  3. If the client has been logged in and has an expired access token, the network will be probed to attempt a refresh of the session. This should not require user interaction. If refresh fails, the user will be prompted to perform a fresh login, requiring user interaction.
  4. If the client has never been logged in and is a user interactive client (verses an M2M client), a user interactive login will be initiated.

There still may be conditions where we believe we are ready, but requests will still ultimately fail. Saved secrets for M2M clients could be wrong, or the user could be denied by API access rules that are independent of session authentication.

When a user interactive login is required, the client must specify whether a local web browser may be opened and/or whether the TTY may be used to prompt the user. What is appropriate will depend on the nature of the application using the Planet SDK.

If the auth context cannot be made ready, an exception will be raised.

Parameters:

Name Type Description Default
allow_open_browser Optional[bool]

specify whether login is permitted to open a local browser window.

False
allow_tty_prompt Optional[bool]

specify whether login is permitted to request input from the terminal.

False

from_env(variable_name=None) staticmethod

Create authentication from environment variables.

Reads the PL_API_KEY environment variable

Pending Deprecation: This method is pending deprecation. The method from_user_default_session() considers environment variables and configuration files through the planet_auth and planet_auth_utils libraries, and works with legacy API keys, OAuth2 M2M clients, and OAuth2 interactive profiles. This method should be used in most cases as a replacement.

Parameters:

Name Type Description Default
variable_name Optional[str]

Alternate environment variable.

None

from_file(filename=None) staticmethod

Create authentication from secret file.

The default secret file is named .planet.json and is stored in the user directory. The file has a special format and should have been created with Auth.write().

Pending deprecation: OAuth2, which should replace API keys in most cases does not have a direct replacement for "from_file()" in many cases. The format of the .planet.json file is changing with the migration of Planet APIs to OAuth2. With that, this method is also being deprecated as a means to bootstrap auth configuration with a simple API key. For the time being this method will still be supported, but this method will fail if the file is present with only new configuration fields, and lacks the legacy API key field.

Parameters:

Name Type Description Default
filename Optional[Union[str, pathlib.Path]]

Alternate path for the planet secret file.

None

from_key(key) staticmethod

Obtain authentication from api key.

Parameters:

Name Type Description Default
key Optional[str]

Planet API key

required

from_oauth_m2m(client_id, client_secret, requested_scopes=None, save_state_to_storage=True, profile_name=None, storage_provider=None) staticmethod

Create authentication from the specified OAuth2 service account client ID and secret.

Parameters:

Name Type Description Default
client_id str

Planet service account client ID.

required
client_secret str

Planet service account client secret.

required
requested_scopes Optional[List[str]]

List of requested OAuth2 scopes

None
profile_name Optional[str]

User friendly name to use when saving the configuration to storage per the save_state_to_storage flag. The profile name will be normalized to a file system compatible identifier regardless of the storage provider being used.

None
save_state_to_storage bool

Boolean controlling whether login sessions should be saved to storage. When the default storage provider is used, they will be stored in a way that is compatible with the planet CLI.

True
storage_provider Optional[planet_auth.ObjectStorageProvider]

A custom storage provider to save session state for the application.

None

from_oauth_user_auth_code(client_id, callback_url, requested_scopes=None, save_state_to_storage=True, profile_name=None, storage_provider=None) staticmethod

Create authentication context for the specified registered client application.

Developers of applications must register clients with Planet, and will be issued a Client ID as part of that process. Developers should register a client for each distinct application so that end-users may discretely manage applications permitted to access Planet APIs on their behalf.

This method does not perform a user login to initialize a session. If not initialized out of band using the CLI, sessions must be initialized with the user_login() before API calls may be made.

Parameters:

Name Type Description Default
client_id str

Client ID

required
requested_scopes Optional[List[str]]

List of requested OAuth2 scopes

None
callback_url str

Client callback URL

required
profile_name Optional[str]

User friendly name to use when saving the configuration to storage per the save_state_to_storage flag. The profile name will be normalized to a file system compatible identifier, regardless of storage provider.

None
save_state_to_storage bool

Boolean controlling whether login sessions should be saved to storage. When the default storage provider is used, they will be stored in a way that is compatible with the planet CLI.

True
storage_provider Optional[planet_auth.ObjectStorageProvider]

A custom storage provider to save session state for the application.

None

from_oauth_user_device_code(client_id, requested_scopes=None, save_state_to_storage=True, profile_name=None, storage_provider=None) staticmethod

Create authentication context for the specified registered client application.

Developers of applications must register clients with Planet, and will be issued a Client ID as part of that process. Developers should register a client for each distinct application so that end-users may discretely manage applications permitted to access Planet APIs on their behalf.

This method does not perform a user login to initialize a session.

This method does not perform a user login to initialize a session. If not initialized out of band using the CLI, sessions must be initialized with the device login methods device_user_login_initiate() and device_user_login_complete() before API calls may be made.

Parameters:

Name Type Description Default
client_id str

Client ID

required
requested_scopes Optional[List[str]]

List of requested OAuth2 scopes

None
profile_name Optional[str]

User friendly name to use when saving the configuration to storage per the save_state_to_storage flag. The profile name will be normalized to file system compatible identifier, regardless of the storage provider being used.

None
save_state_to_storage bool

Boolean controlling whether login sessions should be saved to storage. When the default storage provider is used, they will be stored in a way that is compatible with the planet CLI.

True
storage_provider Optional[planet_auth.ObjectStorageProvider]

A custom storage provider to save session state for the application.

None

from_profile(profile_name, save_state_to_storage=True) staticmethod

Create authentication context from an auth session that has been initialized and saved to ~/.planet.json and ~/.planet/.

Users can initialize and save such a session out-of-band using the planet auth login and planet auth profile commands.

To initialize this session programmatically without the CLI, you must complete an OAuth2 user login flow with one of the login methods on this class. The login method used must be compatible with the specified profile.

This method does not support the use a custom storage provider.

In addition to sharing sessions with other programs through the user's home directory, this method may also be used to load SDK built-in client profiles. This is provided as a developer convenience. Applications should register unique client IDs with the Planet service and use from_oauth_user_auth_code() or from_oauth_user_device_code() to create profiles unique to the application. At present, the following built-in profiles are available:

Profile Name Description
planet-user User interactive OAuth2 client profile shared with the planet CLI.

Parameters:

Name Type Description Default
profile_name str

Named profile from which to load auth configuration and state. This should be a name of a CLI managed profile.

required
save_state_to_storage bool

Boolean controlling whether login sessions should be saved to storage. This nearly always should be true, since this constructor exists to share state through storage backed profiles. The only exception may be when using a SDK built-in profile in an application that should not attempt to save state to disk.

True

from_user_default_session() staticmethod

Create authentication context from user defaults.

This method should be used when an application wants to defer auth profile management to the user and the planet auth CLI command entirely.

Users may use the planet auth login and `planet auth profile commands to initialize and manage sessions.

Defaults take into account environment variables (highest priority), user configuration saved to ~/.planet.json and ~/.planet/ (next priority), and built-in defaults (lowest priority).

This method does not support the use a custom storage provider.

Environment Variables:

Variable Name Description
PL_AUTH_CLIENT_ID Specify an OAuth2 M2M client ID
PL_AUTH_CLIENT_SECRET Specify an OAuth2 M2M client secret
PL_AUTH_API_KEY Specify a legacy Planet API key
PL_AUTH_PROFILE Specify a previously saved planet_auth library auth client profile

is_initialized(self)

Check whether the user session has been initialized. For OAuth2 user based sessions, this means that a login has been performed or saved login session data has been located. For M2M and API Key sessions, this should be true if keys or secrets have been properly configured. The network will not be probed, and the user will not be prompted by this method.

Expired sessions or invalid credentials will not be detected. See ensure_initialized() for a method that will check the validity of sessions.

sync_auth_flow(self, request) inherited

Execute the authentication flow synchronously.

By default, this defers to .auth_flow(). You should override this method when the authentication scheme does I/O and/or uses concurrency primitives.

user_login(self, allow_open_browser=False, allow_tty_prompt=False)

Perform an interactive login. User interaction will be via the TTY and/or a local web browser, with the details dependent on the client auth configuration.

:param allow_open_browser: :param allow_tty_prompt:

Session (BaseSession)

Context manager for asynchronous communication with the Planet service.

The default behavior is to read authentication information stored in the secret file. This behavior can be overridden by providing an auth.Auth instance as an argument.

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         # communicate with services here
...         pass
...
>>> asyncio.run(main())

Examples:

>>> import async
>>> from planet import Auth, Session
>>>
>>> async def main():
...     auth = Auth.from_key('examplekey')
...     async with Session(auth=auth) as sess:
...         # communicate with services here
...         pass
...
>>> asyncio.run(main())

__init__(self, auth=None, read_timeout_secs=None) special

Initialize a Session.

Parameters:

Name Type Description Default
auth Optional[AuthType]

Planet server authentication.

None
read_timeout_secs Optional[float]

Maximum time to wait for data to be received.

None

client(self, name, base_url=None)

Get a client by its module name.

Parameters:

Name Type Description Default
name Literal['data', 'orders', 'subscriptions']

one of 'data', 'orders', or 'subscriptions'.

required

Returns:

Type Description
object

A client instance.

Exceptions:

Type Description
planet.exceptions.ClientError

when no such client can be had.

request(self, method, url, json=None, params=None) async

Build a request and submit it with retry and limiting.

Parameters:

Name Type Description Default
method str

HTTP request method.

required
url str

Location of the API endpoint.

required
json Optional[dict]

JSON to send.

None
params Optional[dict]

Values to send in the query string.

None

Returns:

Type Description
models.Response

Server response.

Exceptions:

Type Description
planet.exceptions.APIException

On API error.

planet.exceptions.ClientError

When retry limit is exceeded.

stream(self, method, url, params=None)

Submit a request and get the response as a stream context manager.

Parameters:

Name Type Description Default
method str

HTTP request method.

required
url str

Location of the API endpoint.

required

Returns:

Type Description
AsyncGenerator[models.StreamingResponse, None]

Context manager providing the streaming response.

MosaicsClient (_BaseClient)

High-level asynchronous access to Planet's Mosaics API.

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         cl = sess.client('mosaics')
...         # use client here
...
>>> asyncio.run(main())

__init__(self, session, base_url=None) special

Parameters:

Name Type Description Default
session Session

Open session connected to server.

required
base_url Optional[str]

The base URL to use. Defaults to production Mosaics base url.

None

download_quad(/, self, quad, *, directory='.', overwrite=False, progress_bar=False) async

Download a quad to a directory.

Examples:

quad = await client.get_quad("d5098531-aa4f-4ff9-a9d5-74ad4a6301e5", "1234-5678")
await client.download_quad(quad)

download_quads(/, self, mosaic, *, directory=None, overwrite=False, bbox=None, geometry=None, progress_bar=False, concurrency=4) async

Download a mosaics' quads to a directory.

Exceptions:

Type Description
ClientError

if geometry or bbox is not specified.

Examples:

mosaic = await cl.get_mosaic(name)
client.download_quads(mosaic, bbox=(-100, 40, -100, 40))

get_mosaic(self, name_or_id) async

Get the API representation of a mosaic by name or id.

Parameters:

Name Type Description Default
name_or_id str

The name or id of the mosaic

required

get_quad(self, mosaic, quad_id) async

Get a mosaic's quad information.

Examples:

quad = await client.get_quad("d5098531-aa4f-4ff9-a9d5-74ad4a6301e5", "1234-5678")
print(quad)

get_quad_contributions(self, quad) async

Get a mosaic's quad information.

Examples:

quad = await client.get_quad("d5098531-aa4f-4ff9-a9d5-74ad4a6301e5", "1234-5678")
contributions = await client.get_quad_contributions(quad)
print(contributions)

get_series(self, name_or_id) async

Get the API representation of a series by name or id.

Parameters:

Name Type Description Default
name_or_id str

The name or id of the mosaic

required

list_mosaics(self, *, name_contains=None, interval=None, acquired_gt=None, acquired_lt=None)

List the mosaics you have access to.

Examples:

mosaics = await client.list_mosaics()
async for m in mosaics:
    print(m)

list_quads(/, self, mosaic, *, minimal=False, full_extent=False, bbox=None, geometry=None)

List the a mosaic's quads.

Parameters:

Name Type Description Default
mosaic Union[planet.models.Mosaic, str]

the mosaic to list

required
minimal bool

if False, response includes full metadata

False
full_extent bool

if True, the mosaic's extent will be used to list

False
bbox Optional[Sequence[Union[int, float]]]

only quads intersecting the bbox will be listed

None
geometry Union[dict, planet.models.GeoInterface]

only quads intersecting the geometry will be listed

None

Exceptions:

Type Description
ClientError

if geometry, bbox or full_extent is not specified.

Examples:

List the quad at a single point (note the extent has the same corners)

mosaic = await client.get_mosaic("d5098531-aa4f-4ff9-a9d5-74ad4a6301e5")
quads = await client.list_quads(mosaic, bbox=[-100, 40, -100, 40])
async for q in quads:
    print(q)

list_series(self, *, name_contains=None, interval=None, acquired_gt=None, acquired_lt=None)

List the series you have access to.

Examples:

series = await client.list_series()
async for s in series:
    print(s)

list_series_mosaics(/, self, series, *, acquired_gt=None, acquired_lt=None, latest=False)

List the mosaics in a series.

Examples:

mosaics = await client.list_series_mosaics("d5098531-aa4f-4ff9-a9d5-74ad4a6301e5")
async for m in mosaics:
    print(m)

summarize_quads(/, self, mosaic, *, bbox=None, geometry=None) async

Get a summary of a quad list for a mosaic.

If the bbox or geometry is not provided, the entire list is considered.

Examples:

Get the total number of quads in the mosaic.

mosaic = await client.get_mosaic("d5098531-aa4f-4ff9-a9d5-74ad4a6301e5")
summary = await client.summarize_quads(mosaic)
print(summary["total_quads"])

OrdersClient (_BaseClient)

High-level asynchronous access to Planet's orders API.

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         cl = sess.client('orders')
...         # use client here
...
>>> asyncio.run(main())

__init__(self, session, base_url=None) special

Parameters:

Name Type Description Default
session Session

Open session connected to server.

required
base_url Optional[str]

The base URL to use. Defaults to production orders API base url.

None

aggregated_order_stats(self) async

Get aggregated counts of active orders.

Returns:

Type Description
dict

Aggregated order counts

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

cancel_order(self, order_id) async

Cancel a queued order.

Parameters:

Name Type Description Default
order_id str

The ID of the order

required

Returns:

Type Description
dict

Results of the cancel request

Exceptions:

Type Description
planet.exceptions.ClientError

If order_id is not a valid UUID.

planet.exceptions.APIError

On API error.

cancel_orders(self, order_ids=None) async

Cancel queued orders in bulk.

Parameters:

Name Type Description Default
order_ids Optional[List[str]]

The IDs of the orders. If empty or None, all orders in a pre-running state will be cancelled.

None

Returns:

Type Description
dict

Results of the bulk cancel request

Exceptions:

Type Description
planet.exceptions.ClientError

If an entry in order_ids is not a valid UUID.

planet.exceptions.APIError

On API error.

create_order(self, request) async

Create an order request.

Examples:

>>> import asyncio
>>> from planet import Session
>>> from planet.order_request import build_request, product
>>>
>>> async def main():
...     image_ids = ["20200925_161029_69_2223"]
...     request = build_request(
...         'test_order',
...         [product(image_ids, 'analytic_udm2', 'psscene')]
...     )
...     async with Session() as sess:
...         cl = sess.client('orders')
...         order = await cl.create_order(request)
...
>>> asyncio.run(main())

Parameters:

Name Type Description Default
request dict

order request definition

required

Returns:

Type Description
dict

JSON description of the created order

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

download_asset(self, location, filename=None, directory=PosixPath('.'), overwrite=False, progress_bar=True) async

Download ordered asset.

Parameters:

Name Type Description Default
location str

Download location url including download token.

required
filename Optional[str]

Custom name to assign to downloaded file.

None
directory Path

Base directory for file download. This directory will be created if it does not already exist.

PosixPath('.')
overwrite bool

Overwrite any existing files.

False
progress_bar bool

Show progress bar during download.

True

Returns:

Type Description
Path

Path to downloaded file.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

download_order(self, order_id, directory=PosixPath('.'), overwrite=False, progress_bar=False) async

Download all assets in an order.

Parameters:

Name Type Description Default
order_id str

The ID of the order.

required
directory Path

Base directory for file download. This directory must already exist.

PosixPath('.')
overwrite bool

Overwrite files if they already exist.

False
progress_bar bool

Show progress bar during download.

False

Returns:

Type Description
List[pathlib.Path]

Paths to downloaded files.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If the order is not in a final state.

get_order(self, order_id) async

Get order details by Order ID.

Parameters:

Name Type Description Default
order_id str

The ID of the order

required

Returns:

Type Description
dict

JSON description of the order

Exceptions:

Type Description
planet.exceptions.ClientError

If order_id is not a valid UUID.

planet.exceptions.APIError

On API error.

list_orders(self, state=None, limit=100, source_type=None, name=None, name__contains=None, created_on=None, last_modified=None, hosting=None, destination_ref=None, sort_by=None, user_id=None)

Iterate over the list of stored orders.

By default, order descriptions are sorted by creation date with the last created order returned first.

Note

The name of this method is based on the API's method name. This method provides iteration over results, it does not get a single result description or return a list of descriptions.

Parameters:

Name Type Description Default
state str

filter by state.

None
limit int

maximum number of results to return. When set to 0, no maximum is applied.

100
source_type str

filter by source type.

None
name str

filter by name.

None
name__contains str

only include orders with names containing this string.

None
created_on str

filter by creation date-time or interval.

None
last_modified str

filter by last modified date-time or interval.

None
hosting bool

only return orders that contain a hosting block (e.g. SentinelHub hosting).

None
destination_ref str

filter by orders created with the provided destination reference.

None
sort_by str

fields to sort orders by. Multiple fields can be specified, separated by commas. The sort direction can be specified by appending ' ASC' or ' DESC' to the field name. The default sort direction is ascending. When multiple fields are specified, the sort order is applied in the order the fields are listed.

Supported fields: name, created_on, state, last_modified

Examples: * "name" * "name DESC" * "name,state DESC,last_modified"

None
user_id str or int

filter by user ID. Only available to organization admins. Accepts "all" or a specific user ID.

None

Datetime args (created_on and last_modified) can either be a date-time or an interval, open or closed. Date and time expressions adhere to RFC 3339. Open intervals are expressed using double-dots.

Examples:

  • A date-time: "2018-02-12T23:20:50Z"
  • A closed interval: "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z"
  • Open intervals: "2018-02-12T00:00:00Z/.." or "../2018-03-18T12:31:12Z"

Yields:

Type Description
AsyncIterator[dict]

Description of an order.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If state is not valid.

validate_checksum(directory, checksum) staticmethod

Validate checksums of downloaded files against order manifest.

For each file entry in the order manifest, the specified checksum given in the manifest file will be validated against the checksum calculated from the downloaded file.

Parameters:

Name Type Description Default
directory Path

Path to order directory.

required
checksum str

The type of checksum hash- 'MD5' or 'SHA256'.

required

Exceptions:

Type Description
planet.exceptions.ClientError

If a file is missing or if checksums do not match.

wait(self, order_id, state=None, delay=5, max_attempts=200, callback=None) async

Wait until order reaches desired state.

Returns the state of the order on the last poll.

This function polls the Orders API to determine the order state, with the specified delay between each polling attempt, until the order reaches a final state, or earlier state, if specified. If the maximum number of attempts is reached before polling is complete, an exception is raised. Setting 'max_attempts' to zero will result in no limit on the number of attempts.

Setting 'delay' to zero results in no delay between polling attempts. This will likely result in throttling by the Orders API, which has a rate limit of 10 requests per second. If many orders are being polled asynchronously, consider increasing the delay to avoid throttling.

By default, polling completes when the order reaches a final state. If 'state' is given, polling will complete when the specified earlier state is reached or passed.

Examples:

from planet.reporting import StateBar

with StateBar() as bar:
    await wait(order_id, callback=bar.update_state)

Parameters:

Name Type Description Default
order_id str

The ID of the order.

required
state Optional[str]

State prior to a final state that will end polling.

None
delay int

Time (in seconds) between polls.

5
max_attempts int

Maximum number of polls. Set to zero for no limit.

200
callback Optional[Callable[[str], NoneType]]

Function that handles state progress updates.

None

Returns State of the order.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If order_id or state is not valid or if the maximum number of attempts is reached before the specified state or a final state is reached.

order_request

Functionality for preparing order details for use in creating an order

amazon_s3(aws_access_key_id, aws_secret_access_key, bucket, aws_region, path_prefix=None)

Amazon S3 Cloud configuration.

Parameters:

Name Type Description Default
aws_access_key_id str

S3 account access key.

required
aws_secret_access_key str

S3 account secret key.

required
bucket str

The name of the bucket that will receive the order output.

required
aws_region str

The region where the bucket lives in AWS.

required
path_prefix Optional[str]

Custom string to prepend to the files delivered to the bucket. A slash (/) character will be treated as a "folder". Any other characters will be added as a prefix to the files.

None

azure_blob_storage(account, container, sas_token, storage_endpoint_suffix=None, path_prefix=None)

Azure Blob Storage configuration.

Parameters:

Name Type Description Default
account str

Azure account.

required
container str

ABS container name.

required
sas_token str

Shared-Access Signature token. Token should be specified without a leading '?'.

required
storage_endpoint_suffix Optional[str]

Deliver order to a sovereign cloud.

None
path_prefix Optional[str]

Custom string to prepend to the files delivered to the bucket. A slash (/) character will be treated as a "folder". Any other characters will be added as a prefix to the files.

None

band_math_tool(b1, b2=None, b3=None, b4=None, b5=None, b6=None, b7=None, b8=None, b9=None, b10=None, b11=None, b12=None, b13=None, b14=None, b15=None, pixel_type='Auto')

Specify an Orders API band math tool.

The parameters of the bandmath tool define how each output band in the derivative product should be produced, referencing the product inputs’ original bands. Band math expressions may not reference neighboring pixels, as non-local operations are not supported. The tool can calculate up to 15 bands for an item. Input band parameters may not be skipped. For example, if the b4 parameter is provided, then b1, b2, and b3 parameters are also required.

For each band expression, the bandmath tool supports normal arithmetic operations and simple math operators offered in the Python numpy package. (For a list of supported mathematical functions, see Band Math documentation).

One bandmath imagery output file is produced for each product bundle, with output bands derived from the band math expressions. nodata pixels are processed with the band math equation. These files have “_bandmath” appended to their file names.

The tool passes through UDM, RPC, and XML files, and does not update values in these files.

Parameters:

Name Type Description Default
b1 str

An expression defining how the output band should be computed.

required
b2 Optional[str]

An expression defining how the output band should be computed.

None
b3 Optional[str]

An expression defining how the output band should be computed.

None
b4 Optional[str]

An expression defining how the output band should be computed.

None
b5 Optional[str]

An expression defining how the output band should be computed.

None
b6 Optional[str]

An expression defining how the output band should be computed.

None
b7 Optional[str]

An expression defining how the output band should be computed.

None
b8 Optional[str]

An expression defining how the output band should be computed.

None
b9 Optional[str]

An expression defining how the output band should be computed.

None
b10 Optional[str]

An expression defining how the output band should be computed.

None
b11 Optional[str]

An expression defining how the output band should be computed.

None
b12 Optional[str]

An expression defining how the output band should be computed.

None
b13 Optional[str]

An expression defining how the output band should be computed.

None
b14 Optional[str]

An expression defining how the output band should be computed.

None
b15 Optional[str]

An expression defining how the output band should be computed.

None
pixel_type str

A value indicating what the output pixel type should be.

'Auto'

Exceptions:

Type Description
planet.exceptions.ClientError

If pixel_type is not valid.

build_request(name, products, subscription_id=0, delivery=None, notifications=None, order_type=None, tools=None, stac=None, hosting=None, collection_id=None, create_configuration=False)

Prepare an order request.

>>> from planet.order_request import (
...     build_request, product, toar_tool, reproject_tool, tile_tool)
...
>>> products = [
...     product(['20170614_113217_3163208_RapidEye-5'],
...             'analytic', 'REOrthoTile')])
... ]
...
>>> tools = [
...     toar_tool(scale_factor=10000),
...     reproject_tool(projection='WSG84', kernel='cubic'),
...     tile_tool(1232, origin_x=-180, origin_y=-90,
...               pixel_size=0.000027056277056,
...               name_template='C1232_30_30_{tilex:04d}_{tiley:04d}')
... ]
...
>>> order_request = build_request(
...     'test_order', products, tools)
...

Parameters:

Name Type Description Default
name str

Name of the order.

required
products List[dict]

Product(s) from the Data API to order.

required
subscription_id int

Apply this orders against this quota subscription.

0
delivery Optional[dict]

Specify custom delivery handling.

None
notifications Optional[dict]

Specify custom notifications handling.

None
order_type Optional[str]

Accept a partial order, indicated by 'partial'.

None
tools Optional[List[dict]]

Tools to apply to the products. Order defines the toolchain order of operations.

None
stac Optional[dict]

Include STAC metadata.

None
hosting Optional[str]

A hosting destination (e.g. Sentinel Hub).

None
collection_id Optional[str]

A Sentinel Hub collection ID.

None
create_configuration Optional[bool]

Automatically create a layer configuration for your collection.

False

Exceptions:

Type Description
planet.specs.SpecificationException

If order_type is not a valid order type.

clip_tool(aoi)

Create the API spec representation of a clip tool.

Examples:

aoi = {
    "type": "Polygon",
    "coordinates": [[
        [37.791595458984375, 14.84923123791421],
        [37.90214538574219, 14.84923123791421],
        [37.90214538574219, 14.945448293647944],
        [37.791595458984375, 14.945448293647944],
        [37.791595458984375, 14.84923123791421]
    ]]
  }
tool = clip_tool(aoi)

Parameters:

Name Type Description Default
aoi dict

clip GeoJSON, either Polygon or Multipolygon.

required

Exceptions:

Type Description
planet.exceptions.ClientError

If GeoJSON is not a valid polygon or multipolygon.

composite_tool(group_by=None)

Create the API spec representation of a composite tool.

Parameters:

Name Type Description Default
group_by Optional[str]

(Optional) Defines how items are grouped to create one or more composites. Supported values are: - "order": All input items are used to create a single composite output. This is the default behavior. - "strip_id": Input items are grouped by their strip_id to create multiple composites.

None

Returns:

Type Description
dict

A dictionary representing the composite tool configuration.

Exceptions:

Type Description
planet.exceptions.ClientError

If group_by is not one of "order" or "strip_id".

coregister_tool(anchor_item)

Create the API spec representation of a coregister tool.

Parameters:

Name Type Description Default
anchor_item str

The item_id of the item to which all other items should be coregistered.

required

default_destination(path_prefix=None)

Default Destinations API configuration.

Parameters:

Name Type Description Default
path_prefix Optional[str]

Path prefix for deliveries.

None

delivery(archive_type=None, single_archive=False, archive_filename=None, cloud_config=None)

Order delivery configuration.

Examples:

amazon_s3_config = amazon_s3(
    'access_key',
    'secret_access_key',
    'bucket_name',
    'us-east-2',
    'folder1/prefix/'
)
delivery_config = delivery(
    archive_type='zip',
    single_archive=True,
    archive_filename='{{order_id}}.zip'
    cloud_config=amazon_s3_config
)

Parameters:

Name Type Description Default
archive_type Optional[str]

Archive order files. Only supports 'zip'.

None
single_archive Optional[bool]

Archive all bundles together in a single file.

False
archive_filename Optional[str]

Custom naming convention to use to name the archive file that is received. Uses the template variables {{name}} and {{order_id}}. e.g. "{{name}}_{{order_id}}.zip".

None
cloud_config Optional[Mapping]

Cloud delivery configuration.

None

Exceptions:

Type Description
planet.specs.SpecificationException

If archive_type is not valid.

destination(destination_ref, path_prefix=None)

Destinations API configuration.

Parameters:

Name Type Description Default
destination_ref str

Reference to an existing Destinations API destination.

required
path_prefix Optional[str]

Path prefix for deliveries.

None

file_format_tool(file_format)

Create the API spec representation of a file format tool.

Parameters:

Name Type Description Default
file_format str

The format of the tool output. Either 'COG' or 'PL_NITF'.

required

Exceptions:

Type Description
planet.specs.SpecificationException

If file_format is not one of 'COG' or 'PL_NITF'

google_cloud_storage(bucket, credentials, path_prefix=None)

Google Cloud Storage configuration.

Parameters:

Name Type Description Default
bucket str

GCS bucket name.

required
credentials str

JSON-string of service account for bucket.

required
path_prefix Optional[str]

Custom string to prepend to the files delivered to the bucket. A slash (/) character will be treated as a "folder". Any other characters will be added as a prefix to the files.

None

google_earth_engine(project, collection)

Google Earth Engine configuration.

Parameters:

Name Type Description Default
project str

GEE project name.

required
collection str

GEE Image Collection name.

required

harmonize_tool(target_sensor)

Create the API spec representation of a harmonize tool.

Parameters:

Name Type Description Default
target_sensor str

A value indicating to what sensor the input asset types should be calibrated.

required

Exceptions:

Type Description
planet.exceptions.ClientError

If target_sensor is not valid.

notifications(email=None, webhook_url=None, webhook_per_order=None)

Notifications description for an order detail.

Parameters:

Name Type Description Default
email Optional[bool]

Enable email notifications for an order.

None
webhook_url Optional[str]

URL for notification when the order is ready.

None
webhook_per_order Optional[bool]

Request a single webhook call per order instead of one call per each delivered item.

None

oracle_cloud_storage(customer_access_key_id, customer_secret_key, bucket, region, namespace, path_prefix=None)

Oracle Cloud Storage configuration.

Parameters:

Name Type Description Default
customer_access_key_id str

Customer Access Key credentials.

required
customer_secret_key str

Customer Secret Key credentials.

required
bucket str

The name of the bucket that will receive the order output.

required
region str

The region where the bucket lives in Oracle.

required
namespace str

Object Storage namespace name.

required
path_prefix Optional[str]

Custom string to prepend to the files delivered to the bucket. A slash (/) character will be treated as a "folder". Any other characters will be added as a prefix to the files.

None

product(item_ids, product_bundle, item_type, fallback_bundle=None)

Product description for an order detail.

Parameters:

Name Type Description Default
item_ids List[str]

IDs of the catalog items to include in the order.

required
product_bundle str

Set of asset types for the catalog items.

required
item_type str

The class of spacecraft and processing characteristics for the catalog items.

required
fallback_bundle Optional[Union[str, List[str]]]

In case of product_bundle not having all asset types available, which would result in failed delivery, try one or more fallback bundles. Multiple fallback bundles may be provided as a list or a comma separated string.

None

Exceptions:

Type Description
planet.specs.SpecificationException

If bundle or fallback bundle are not valid bundles or if item_type is not valid for the given bundle or fallback bundle.

reproject_tool(projection, resolution=None, kernel=None)

Create the API spec representation of a reproject tool.

Parameters:

Name Type Description Default
projection str

A coordinate system in the form EPSG:n. (ex. EPSG:4326 for WGS84, EPSG:32611 for UTM 11 North (WGS84), or EPSG:3857 for Web Mercator).

required
resolution Optional[float]

The pixel width and height in the output file. The API default is the resolution of the input item. This value will be in meters unless the coordinate system is geographic (like EPSG:4326), then it will be a pixel size in decimal degrees.

None
kernel Optional[str]

The resampling kernel used. The API default is "near". This parameter also supports "bilinear", "cubic", "cubicspline", "lanczos", "average" and "mode".

None

s3_compatible(endpoint, bucket, region, access_key_id, secret_access_key, use_path_style=False, path_prefix=None)

S3 Compatible configuration.

Parameters:

Name Type Description Default
endpoint str

S3 compatible endpoint.

required
bucket str

S3-compatible bucket that will receive the order output.

required
region str

Region where the bucket lives in the s3 compatible service.

required
access_key_id str

Access key for authentication.

required
secret_access_key str

Secret key for authentication.

required
use_path_style bool

Use path-style addressing with bucket name in URL (default is False).

False
path_prefix Optional[str]

Custom string to prepend to the files delivered to the bucket. A slash (/) character will be treated as a "folder". Any other characters will be added as a prefix to the files.

None

sentinel_hub(collection_id=None, create_configuration=False)

Specify a Sentinel Hub hosting destination.

tile_tool(tile_size, origin_x=None, origin_y=None, pixel_size=None, name_template=None, conformal_x_scaling=None)

Create the API spec representation of a reproject tool.

Parameters:

Name Type Description Default
tile_size int

Height and width of output tiles in pixels and lines (always square).

required
origin_x Optional[float]

Tiling system x origin in projected coordinates. The API default is zero.

None
origin_y Optional[float]

Tiling system y origin in projected coordinates. The API default is zero.

None
pixel_size Optional[float]

Tiling system pixel size in projected coordinates. The API default is the pixel_size of input raster.

None
name_template Optional[str]

A naming template for creating output tile filenames. The API default is "{tilex}_{tiley}.tif" resulting in filenames like 128_200.tif. The {tilex} and {tiley} parameters can be of the form {tilex:06d} to produce a fixed width field with leading zeros.

None

toar_tool(scale_factor=None)

Create the API spec representation of a TOAR tool.

Parameters:

Name Type Description Default
scale_factor Optional[int]

Scale factor applied to convert 0.0 to 1.0 reflectance floating point values to a value that fits in 16bit integer pixels. The API default is 10000. Values over 65535 could result in high reflectances not fitting in 16bit integers.

None

DataClient (_BaseClient)

High-level asynchronous access to Planet's data API.

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         cl = sess.client('data')
...         # use client here
...
>>> asyncio.run(main())

activate_asset(self, asset) async

Activate an item asset.

Parameters:

Name Type Description Default
asset dict

Description of the asset. Obtained from get_asset().

required

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If asset description is not valid.

Create a new saved structured item search.

To filter to items you have access to download which are of standard (aka not test) quality, use the following:

>>> from planet import data_filter
>>> data_filter.and_filter([
...     data_filter.permission_filter(),
...     data_filter.std_quality_filter()
>>> ])

To avoid filtering out any imagery, supply a blank AndFilter, which can be created with data_filter.and_filter([]).

Parameters:

Name Type Description Default
item_types List[str]

The item types to include in the search.

required
search_filter dict

Structured search criteria.

required
name str

The name of the saved search.

required
enable_email bool

Send a daily email when new results are added.

False
geometry Union[dict, str]

A feature reference or a GeoJSON

None

Returns:

Type Description
dict

Description of the saved search.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

Delete an existing saved search.

Parameters:

Name Type Description Default
search_id str

Saved search identifier.

required

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

download_asset(self, asset, filename=None, directory=PosixPath('.'), overwrite=False, progress_bar=True) async

Download an asset.

The asset must be active before it can be downloaded. This can be achieved with activate_asset() followed by wait_asset().

If overwrite is False and the file already exists, download will be skipped and the file path will be returned as usual.

Parameters:

Name Type Description Default
asset dict

Description of the asset. Obtained from get_asset() or wait_asset().

required
filename Optional[str]

Custom name to assign to downloaded file.

None
directory Path

Base directory for file download.

PosixPath('.')
overwrite bool

Overwrite any existing files.

False
progress_bar bool

Show progress bar during download.

True

Returns:

Type Description
Path

Path to downloaded file.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If asset is not active or asset description is not valid.

get_asset(self, item_type_id, item_id, asset_type_id) async

Get an item asset description.

Parameters:

Name Type Description Default
item_type_id str

Item type identifier.

required
item_id str

Item identifier.

required
asset_type_id str

Asset type identifier.

required

Returns:

Type Description
dict

Description of the asset.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If asset type identifier is not valid.

get_item(self, item_type_id, item_id) async

Get an item by item_type_id and item_id.

Parameters:

Name Type Description Default
item_type_id str

Item type identifier.

required
item_id str

Item identifier.

required

Returns:

Type Description
dict

Description of an item.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

get_item_coverage(self, item_type_id, item_id, geometry, mode=None, band=None) async

Estimate the clear coverage over an item within a custom AOI

Parameters:

Name Type Description Default
item_type_id str

Item type identifier.

required
item_id str

Item identifier.

required
geometry Union[planet.models.Feature, dict, str]

A feature reference or a GeoJSON

required
mode Optional[str]

Method used for coverage calculation

None
band Optional[str]

Specific band to extract from UDM2

None

Returns:

Type Description
dict

Description of the clear coverage for the provided AOI within the scene.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

Get a saved search by id.

Parameters:

Name Type Description Default
search_id str

Stored search identifier.

required

Returns:

Type Description
dict

Saved search details.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

get_stats(self, item_types, search_filter, interval) async

Get item search statistics.

Parameters:

Name Type Description Default
item_types List[str]

The item types to include in the search.

required
search_filter dict

Structured search criteria.

required
interval str

The size of the histogram date buckets.

required

Returns:

Type Description
dict

A full JSON description of the returned statistics result histogram.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If interval is not valid.

list_item_assets(self, item_type_id, item_id) async

List all assets available for an item.

An asset describes a product that can be derived from an item's source data, and can be used for various analytic, visual or other purposes. These are referred to as asset_types.

Parameters:

Name Type Description Default
item_type_id str

Item type identifier.

required
item_id str

Item identifier.

required

Returns:

Type Description
dict

Descriptions of available assets as a dictionary with asset_type_id as keys and asset description as value.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

list_searches(self, sort='created desc', search_type='any', limit=100)

Iterate through list of searches available to the user.

Note

The name of this method is based on the API's method name. This method provides iteration over results, it does not get a single result description or return a list of descriptions.

Parameters:

Name Type Description Default
sort str

Field and direction to order results by.

'created desc'
search_type str

Filter to specified search type.

'any'
limit int

Maximum number of results to return. When set to 0, no maximum is applied.

100

Yields:

Type Description
AsyncIterator[dict]

Description of a search.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If sort or search_type are not valid.

Iterate over results from a saved search.

Note

The name of this method is based on the API's method name. This method provides iteration over results, it does not get a single result description or return a list of descriptions.

Parameters:

Name Type Description Default
search_id str

Stored search identifier.

required
sort Optional[str]

Field and direction to order results by. Valid options are given in SEARCH_SORT.

None
limit int

Maximum number of results to return. When set to 0, no maximum is applied.

100

Yields:

Type Description
AsyncIterator[dict]

Description of an item.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If search_id or sort is not valid.

search(self, item_types, search_filter=None, name=None, sort=None, limit=100, geometry=None)

Iterate over results from a quick search.

Quick searches are saved for a short period of time (~month). The name parameter of the search defaults to the id of the generated search id if name is not specified.

Note

The name of this method is based on the API's method name. This method provides iteration over results, it does not get a single result description or return a list of descriptions.

Parameters:

Name Type Description Default
item_types List[str]

The item types to include in the search.

required
search_filter Optional[dict]

Structured search criteria to apply. If None, no search criteria is applied.

None
sort Optional[str]

Field and direction to order results by. Valid options are given in SEARCH_SORT.

None
name Optional[str]

The name of the saved search.

None
limit int

Maximum number of results to return. When set to 0, no maximum is applied.

100
geometry Union[planet.models.Feature, dict, str]

GeoJSON, a feature reference or a list of feature references

None

Yields:

Type Description
AsyncIterator[dict]

Description of an item.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

Update an existing saved search.

Parameters:

Name Type Description Default
search_id str

Saved search identifier.

required
item_types List[str]

The item types to include in the search.

required
search_filter dict

Structured search criteria.

required
name str

The name of the saved search.

required
enable_email bool

Send a daily email when new results are added.

False
geometry Union[dict, str]

A feature reference or a GeoJSON

None

Returns:

Type Description
dict

Description of the saved search.

validate_checksum(asset, filename) staticmethod

Validate checksum of downloaded file

Compares checksum calculated from the file against the value provided in the asset.

Parameters:

Name Type Description Default
asset dict

Description of the asset. Obtained from get_asset() or wait_asset().

required
filename Path

Full path to downloaded file.

required

Exceptions:

Type Description
planet.exceptions.ClientError

If the file does not exist or if checksums do not match.

wait_asset(self, asset, delay=5, max_attempts=200, callback=None) async

Wait for an item asset to be active.

Prior to waiting for the asset to be active, be sure to activate the asset with activate_asset().

Parameters:

Name Type Description Default
asset dict

Description of the asset. Obtained from get_asset().

required
delay int

Time (in seconds) between polls.

5
max_attempts int

Maximum number of polls. When set to 0, no limit is applied.

200
callback Optional[Callable[[str], NoneType]]

Function that handles state progress updates.

None

Returns:

Type Description
Dict[Any, Any]

Last received description of the asset.

Exceptions:

Type Description
planet.exceptions.APIError

On API error.

planet.exceptions.ClientError

If asset_type_id is not valid or is not available or if the maximum number of attempts is reached before the asset is active.

data_filter

Functionality for preparing a data search filter

and_filter(nested_filters)

Create an AndFilter

The AndFilter can be used to limit results to items with properties or permissions which match all nested filters.

It is most commonly used as a top-level filter to ensure criteria across all field and permission filters are met.

Parameters:

Name Type Description Default
nested_filters List[dict]

Filters to AND together

required

asset_filter(asset_types)

Create an AssetFilter

The AssetFilter can be used to search for items which have published a specified asset_type. This filter is commonly used to filter items by published asset types which:

  • May be published at delay after an item's first publish. analytic_sr, for instance, may be published up to 12 hours after an item first becomes available.
  • May not be available for the full catalog. udm2, for instance, is only available globally through July 2018.

Filters to all items which include any of the listed asset types. An AndFilter can be used to filter items by multiple asset types.

Parameters:

Name Type Description Default
asset_types List[str]

List of the names of the asset type to filter on.

required

date_range_filter(field_name, gt=None, lt=None, gte=None, lte=None)

Create a DateRangeFilter

The DateRangeFilter can be used to search on any property with a timestamp such as acquired or published.

One or more of the conditional parameters gt, lt, gte, lte must be specified. Conditionals are combined in a logical AND, so only items that match all specified conditionals are returned.

Parameters:

Name Type Description Default
field_name str

Name of field to filter on.

required
gt Optional[datetime.datetime]

Filter to field timestamp later than this datetime.

None
lt Optional[datetime.datetime]

Filter to field timestamp earlier than this datetime.

None
gte Optional[datetime.datetime]

Filter to field timestamp at or later than this datetime.

None
lte Optional[datetime.datetime]

Filter to field timestamp at or earlier than this datetime.

None

Exceptions:

Type Description
exceptions.PlanetError

If no conditional parameter is specified.

empty_filter()

Create an Empty filter for bypassing search filtering.

geometry_filter(geom, relation=None)

Create a GeometryFilter

The GeometryFilter can be used to search for items with a footprint geometry which intersects with the specified geometry.

In cases where a GeoJSON Feature or FeatureCollection are provided, the GeoJSON geometry will be extracted and used in the filter definition.

The filter's configuration supports Point, MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon GeoJSON object. For best results, the geometry should meet OpenGIS Simple Features Interface Specification requirements. If an invalid GeoJSON object is supplied, the API will automatically attempt to correct the geometry and return matching search results.

Parameters:

Name Type Description Default
geom dict

GeoJSON describing the filter geometry, feature, or feature collection.

required
relation Optional[str]

Optional geometry search refinement, defaults to intersects. May also be contains, within, or disjoint.

None

not_filter(nested_filter)

Create a NotFilter

The NotFilter can be used to match items with properties or permissions which do not match the nested filter.

This filter only supports a single nested filter. Multiple NotFilters can be nested within an AndFilter to filter across multiple fields or permission values.

Parameters:

Name Type Description Default
nested_filter dict

Filter to NOT

required

number_in_filter(field_name, values)

Create a NumberInFilter

The NumberInFilter can be used to search for items with numerical poperties. It is useful for matching fields such as gsd.

Parameters:

Name Type Description Default
field_name str

Name of field to filter on.

required
values List[float]

List of numbers to filter on.

required

or_filter(nested_filters)

Create an OrFilter

The OrFilter can be used to match items with properties or permissions which match at least one of the nested filters.

Parameters:

Name Type Description Default
nested_filters List[dict]

Filters to OR together

required

permission_filter()

Create a PermissionFilter

The PermissionFilter limits results to items that a user has permission to download.

range_filter(field_name, gt=None, lt=None, gte=None, lte=None)

Create a RangeFilter

The RangeFilter can be used to search for items with numerical properties. It is useful for matching fields that have a continuous range of values such as cloud_cover or view_angle.

One or more of the conditional parameters gt, lt, gte, lte must be specified. Conditionals are combined in a logical AND, so only items that match all specified conditionals are returned.

Parameters:

Name Type Description Default
field_name str

Name of field to filter on.

required
gt Optional[float]

Filter to field value greater than this number.

None
lt Optional[float]

Filter to field value less than this number.

None
gte Optional[float]

Filter to field value greater than or equal to this number.

None
lte Optional[float]

Filter to field value less than or equal to this number.

None

Exceptions:

Type Description
exceptions.PlanetError

If no conditional parameter is specified.

std_quality_filter()

Create a filter for standard-quality items.

This is a custom filter which filters to items that are categorized as standard quality.

string_in_filter(field_name, values)

Create a StringInFilter

The StringInFilter can be used to search for items with string properties such as instrument or quality_category. Boolean properties such as ground_control are also supported with the StringInFilter.

Filters to items with the given field matching any of the values.

Parameters:

Name Type Description Default
field_name str

Name of field to filter on.

required
values List[str]

List of strings to filter on.

required

update_filter(field_name, gt=None, lt=None, gte=None, lte=None)

Create an UpdateFilter

The UpdateFilter can be used to filter items by changes to a specified metadata field value made after a specified date, due to a republishing event. This feature allows you identify items which may have been republished with improvements or fixes, enabling you to keep your internal catalogs up-to-date and make more informed redownload decisions. The filter works for all items published on or after April 10, 2020.

One or more of the conditional parameters gt or gte must be specified. Conditionals are combined in a logical AND, so only items that match all specified conditionals are returned.

Parameters:

Name Type Description Default
field_name str

Name of field to filter on.

required
gt Optional[float]

Filter to changes to field metadata after this datetime.

None
gte Optional[float]

Filter to changes to field metadata at or after this datetime.

None

Exceptions:

Type Description
exceptions.PlanetError

If no conditional parameter is specified.

SubscriptionsClient (_BaseClient)

A Planet Subscriptions Service API 1.0.0 client.

The methods of this class forward request parameters to the operations described in the Planet Subscriptions Service API 1.0.0 (https://api.planet.com/subscriptions/v1/spec) using HTTP 1.1.

The methods generally return or yield Python dicts with the same structure as the JSON messages used by the service API. Many of the exceptions raised by this class are categorized by HTTP client (4xx) or server (5xx) errors. This client's level of abstraction is low.

High-level asynchronous access to Planet's subscriptions API:

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         cl = sess.client('subscriptions')
...         # use client here
...
>>> asyncio.run(main())

__init__(self, session, base_url=None) special

Parameters:

Name Type Description Default
session Session

Open session connected to server.

required
base_url Optional[str]

The base URL to use. Defaults to production subscriptions API base url.

None

bulk_create_subscriptions(self, requests) async

Create multiple subscriptions in bulk. Currently, the list of requests can only contain one item.

Parameters:

Name Type Description Default
requests List[dict]

A list of dictionaries where each dictionary represents a subscription to be created.

required

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

Returns:

Type Description
Dict

The response including a _links key to the list endpoint for use finding the created subscriptions.

bulk_reactivate_subscriptions(self, subscription_ids=None, all_subscriptions=False) async

Reactivate multiple Subscriptions.

This method supports three modes of operation:

  1. Reactivate specific subscriptions: provide subscription_ids
  2. Reactivate all user's subscriptions: call with no parameters
  3. Reactivate all organization subscriptions: set all_subscriptions=True (organization admin only)

Parameters:

Name Type Description Default
subscription_ids List[str]

list of subscription ids to reactivate. If not provided and all_subscriptions is False, reactivates all of the user's subscriptions.

None
all_subscriptions bool

if True, reactivate all subscriptions for the organization (requires organization admin permissions). Mutually exclusive with subscription_ids.

False

Returns:

Type Description
None

None

Exceptions:

Type Description
ClientError

if both subscription_ids and all_subscriptions are provided.

APIError

on an API server error.

bulk_suspend_subscriptions(self, subscription_ids=None, details=None, all_subscriptions=False) async

Suspend multiple Subscriptions.

This method supports three modes of operation:

  1. Suspend specific subscriptions: provide subscription_ids
  2. Suspend all user's subscriptions: call with no parameters
  3. Suspend all organization subscriptions: set all_subscriptions=True (organization admin only)

Parameters:

Name Type Description Default
subscription_ids List[str]

list of subscription ids to suspend. If not provided and all_subscriptions is False, suspends all of the user's subscriptions.

None
details str

optional details explaining the reason for suspension.

None
all_subscriptions bool

if True, suspend all subscriptions for the organization (requires organization admin permissions). Mutually exclusive with subscription_ids.

False

Returns:

Type Description
None

None

Exceptions:

Type Description
ClientError

if both subscription_ids and all_subscriptions are provided.

APIError

on an API server error.

cancel_subscription(self, subscription_id) async

Cancel a Subscription.

Parameters:

Name Type Description Default
subscription_id str

id of subscription to cancel.

required

Returns:

Type Description
None

None

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

create_subscription(self, request) async

Create a Subscription.

Parameters:

Name Type Description Default
request dict

description of a subscription.

required

Returns:

Type Description
dict

description of created subscription.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

get_results(self, subscription_id, status=None, limit=100, created=None, updated=None, completed=None, item_datetime=None)

Iterate over results of a Subscription.

Notes

The name of this method is based on the API's method name. This method provides iteration over results, it does not get a single result description or return a list of descriptions.

Parameters:

Name Type Description Default
subscription_id str

id of a subscription.

required
status Set[str]

pass result with status in this set, filter out results with status not in this set.

None
limit int

limit the number of subscriptions in the results. When set to 0, no maximum is applied.

100
created str

filter by created time or interval.

None
updated str

filter by updated time or interval.

None
completed str

filter by completed time or interval.

None
item_datetime str

filter by item datetime or interval.

None

Datetime args (created, updated, completed, item_datetime) can either be a date-time or an interval, open or closed. Date and time expressions adhere to RFC 3339. Open intervals are expressed using double-dots.

Examples:

  • A date-time: "2018-02-12T23:20:50Z"
  • A closed interval: "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z"
  • Open intervals: "2018-02-12T00:00:00Z/.." or "../2018-03-18T12:31:12Z"

Yields:

Type Description
dict

description of a subscription results.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

get_results_csv(self, subscription_id, status=None, created=None, updated=None, completed=None, item_datetime=None)

Iterate over rows of results CSV for a Subscription.

Parameters:

Name Type Description Default
subscription_id str

id of a subscription.

required
status Set[str]

pass result with status in this set, filter out results with status not in this set.

None
created str

filter by created time or interval.

None
updated str

filter by updated time or interval.

None
completed str

filter by completed time or interval.

None
item_datetime str

filter by item datetime or interval.

None

Datetime args (created, updated, completed, item_datetime) can either be a date-time or an interval, open or closed. Date and time expressions adhere to RFC 3339. Open intervals are expressed using double-dots.

Examples:

  • A date-time: "2018-02-12T23:20:50Z"
  • A closed interval: "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z"
  • Open intervals: "2018-02-12T00:00:00Z/.." or "../2018-03-18T12:31:12Z"

Yields:

Type Description
str

a row from a CSV file.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

get_subscription(self, subscription_id) async

Get a description of a Subscription.

Parameters:

Name Type Description Default
subscription_id str

id of a subscription.

required

Returns:

Type Description
dict

description of the subscription.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

get_subscription_summary(self, subscription_id) async

Summarize the status of results for a single subscription via GET.

Parameters:

Name Type Description Default
subscription_id str

ID of the subscription to summarize.

required

Returns:

Type Description
dict

result totals for the provided subscription by status.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

get_summary(self) async

Summarize the status of all subscriptions via GET.

Returns:

Type Description
dict

subscription totals by status.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

list_subscriptions(self, status=None, limit=100, created=None, end_time=None, hosting=None, name__contains=None, name=None, source_type=None, start_time=None, sort_by=None, updated=None, destination_ref=None, user_id=None, page_size=500)

Iterate over list of account subscriptions with optional filtering.

Note

The name of this method is based on the API's method name. This method provides iteration over subscriptions, it does not return a list.

Parameters:

Name Type Description Default
status Set[str]

include subscriptions with a status in this set.

None
limit int

limit the number of subscriptions in the results. When set to 0, no maximum is applied.

100
created str

filter by created time or interval.

None
end_time str

filter by end time or interval.

None
hosting bool

only return subscriptions that contain a hosting block (e.g. SentinelHub hosting).

None
name__contains str

only return subscriptions with a name that contains the given string.

None
name str

filter by name.

None
source_type str

filter by source type.

None
start_time str

filter by start time or interval.

None
sort_by str

fields to sort subscriptions by. Multiple fields can be specified, separated by commas. The sort direction can be specified by appending ' ASC' or ' DESC' to the field name. The default sort direction is ascending. When multiple fields are specified, the sort order is applied in the order the fields are listed.

Supported fields: name, created, updated, start_time, end_time

Examples: * "name" * "name DESC" * "name,end_time DESC,start_time"

None
updated str

filter by updated time or interval.

None
destination_ref str

filter by subscriptions created with the provided destination reference.

None
user_id str or int

filter by user ID. Only available to organization admins. Accepts "all" or a specific user ID.

None
page_size int

number of subscriptions to return per page.

500

Datetime args (created, end_time, start_time, updated) can either be a date-time or an interval, open or closed. Date and time expressions adhere to RFC 3339. Open intervals are expressed using double-dots.

Examples:

  • A date-time: "2018-02-12T23:20:50Z"
  • A closed interval: "2018-02-12T00:00:00Z/2018-03-18T12:31:12Z"
  • Open intervals: "2018-02-12T00:00:00Z/.." or "../2018-03-18T12:31:12Z"

Yields:

Type Description
dict

a description of a subscription.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

patch_subscription(self, subscription_id, request) async

Update (edit) a Subscription via PATCH.

Parameters:

Name Type Description Default
subscription_id str

id of the subscription to update.

required
request dict

subscription content for update, only attributes to update are required.

required

Returns:

Type Description
dict

description of the updated subscription.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

reactivate_subscription(self, subscription_id) async

Reactivate a Subscription.

Parameters:

Name Type Description Default
subscription_id str

id of subscription to reactivate.

required

Returns:

Type Description
None

None

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

suspend_subscription(self, subscription_id, details=None) async

Suspend a Subscription.

Parameters:

Name Type Description Default
subscription_id str

id of subscription to suspend.

required
details str

optional details explaining the reason for suspension.

None

Returns:

Type Description
dict

the suspended subscription.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

update_subscription(self, subscription_id, request) async

Update (edit) a Subscription via PUT.

Parameters:

Name Type Description Default
subscription_id str

id of the subscription to update.

required
request dict

subscription content for update, full payload is required.

required

Returns:

Type Description
dict

description of the updated subscription.

Exceptions:

Type Description
APIError

on an API server error.

ClientError

on a client error.

subscription_request

Functionality for preparing subscription requests.

FilterValue dataclass

Represents a filter value with optional greater than or equal to (gte) and less than or equal to (lte) constraints.

Attributes:

Name Type Description
gte Optional[float]

The minimum threshold value for the filter.

lte Optional[float]

The maximum threshold value for the filter.

amazon_s3(aws_access_key_id, aws_secret_access_key, bucket, aws_region, path_prefix=None)

Delivery to Amazon S3.

Parameters:

Name Type Description Default
aws_access_key_id str

S3 account access key.

required
aws_secret_access_key str

S3 account secret key.

required
bucket str

The name of the bucket that will receive the subscription output.

required
aws_region str

The region where the bucket lives in AWS.

required
path_prefix Optional[str]

Path prefix for deliveries.

None

azure_blob_storage(account, container, sas_token, storage_endpoint_suffix=None, path_prefix=None)

Delivery to Azure Blob Storage.

Parameters:

Name Type Description Default
account str

Azure account.

required
container str

ABS container name.

required
sas_token str

Shared-Access Signature token. Token should be specified without a leading '?'.

required
storage_endpoint_suffix Optional[str]

Deliver subscription to a sovereign cloud. The default is "core.windows.net".

None
path_prefix Optional[str]

Path prefix for deliveries.

None

band_math_tool(b1, b2=None, b3=None, b4=None, b5=None, b6=None, b7=None, b8=None, b9=None, b10=None, b11=None, b12=None, b13=None, b14=None, b15=None, pixel_type='Auto')

Specify a subscriptions API band math tool.

The parameters of the bandmath tool define how each output band in the derivative product should be produced, referencing the product inputs’ original bands. Band math expressions may not reference neighboring pixels, as non-local operations are not supported. The tool can calculate up to 15 bands for an item. Input band parameters may not be skipped. For example, if the b4 parameter is provided, then b1, b2, and b3 parameters are also required.

For each band expression, the bandmath tool supports normal arithmetic operations and simple math operators offered in the Python numpy package. (For a list of supported mathematical functions, see Band Math documentation).

One bandmath imagery output file is produced for each product bundle, with output bands derived from the band math expressions. nodata pixels are processed with the band math equation. These files have “_bandmath” appended to their file names.

The tool passes through UDM, RPC, and XML files, and does not update values in these files.

Parameters:

Name Type Description Default
b1 str

An expression defining how the output band should be computed.

required
b2 Optional[str]

An expression defining how the output band should be computed.

None
b3 Optional[str]

An expression defining how the output band should be computed.

None
b4 Optional[str]

An expression defining how the output band should be computed.

None
b5 Optional[str]

An expression defining how the output band should be computed.

None
b6 Optional[str]

An expression defining how the output band should be computed.

None
b7 Optional[str]

An expression defining how the output band should be computed.

None
b8 Optional[str]

An expression defining how the output band should be computed.

None
b9 Optional[str]

An expression defining how the output band should be computed.

None
b10 Optional[str]

An expression defining how the output band should be computed.

None
b11 Optional[str]

An expression defining how the output band should be computed.

None
b12 Optional[str]

An expression defining how the output band should be computed.

None
b13 Optional[str]

An expression defining how the output band should be computed.

None
b14 Optional[str]

An expression defining how the output band should be computed.

None
b15 Optional[str]

An expression defining how the output band should be computed.

None
pixel_type str

A value indicating what the output pixel type should be.

'Auto'

Exceptions:

Type Description
planet.exceptions.ClientError

If pixel_type is not valid.

build_request(name, source, delivery=None, notifications=None, tools=None, hosting=None, collection_id=None, create_configuration=False, clip_to_source=False)

Construct a Subscriptions API request.

The return value can be passed to planet.clients.subscriptions.SubscriptionsClient.create_subscription.

Parameters:

Name Type Description Default
name str

Name of the subscription.

required
source Mapping

A source for the subscription, i.e. catalog.

required
delivery Optional[Mapping]

A delivery mechanism e.g. GCS, AWS, Azure, or OCS.

None
notifications Optional[Mapping]

Specify notifications via email/webhook.

None
tools Optional[List[Mapping]]

Tools to apply to the products. The order of operation is determined by the service.

None
hosting Union[Mapping, str]

A hosting destination e.g. Sentinel Hub.

None
collection_id Optional[str]

A Sentinel Hub collection ID.

None
create_configuration Optional[bool]

Automatically create a layer configuration for your collection.

False
clip_to_source Optional[bool]

Whether or not to clip to the source geometry (defaults to False). If True, a clip configuration will be added to the list of requested tools that automatically clips to the subscription source geometry. If True and a clip tool is also specified in the tools list, an exception will be raised. If False, no clip configuration will be added to the list of requested tools.

False

Returns:

Type Description
dict

a representation of a Subscriptions API request for a new subscription.

Exceptions:

Type Description
ClientError

when a valid Subscriptions API request can't be constructed.

Example::

from datetime import datetime
from planet.subscription_request import build_request, catalog_source, amazon_s3

geom = {
    "coordinates": [
        [
            [139.5648193359375, 35.42374884923695],
            [140.1031494140625, 35.42374884923695],
            [140.1031494140625, 35.77102915686019],
            [139.5648193359375, 35.77102915686019],
            [139.5648193359375, 35.42374884923695],
        ]
    ],
    "type": "Polygon",
}

source = catalog_source(["PSScene"], ["ortho_analytic_4b"], geom, datetime(2021, 3, 1))

delivery = amazon_s3(ACCESS_KEY_ID, SECRET_ACCESS_KEY, "test", "us-east-1")

hosting = sentinel_hub("2716077c-191e-4e47-9e3f-01c9c429f88d")

subscription_request = build_request(
    "test_subscription", source=source, delivery=delivery, hosting=hosting
)

catalog_source(item_types, asset_types, geometry, start_time, filter=None, end_time=None, rrule=None, publishing_stages=None, time_range_type=None, geometry_relation=None)

Construct a Catalog subscription source.

The return value can be passed to planet.subscription_request.build_request.

Parameters:

Name Type Description Default
item_types List[str]

The class of spacecraft and processing level of the subscription's matching items, e.g. PSScene.

required
asset_types List[str]

The data products which will be delivered for all subscription matching items. An item will only match and deliver if all specified asset types are published for that item.

required
geometry Union[dict, str]

The area of interest of the subscription that will be used to determine matches. Can be either a geojson-like dict or a Features API feature reference (string)

required
start_time datetime

The start time of the subscription. This time can be in the past or future.

required
filter Optional[Mapping]

The filter criteria based on item-level metadata.

None
end_time Optional[datetime.datetime]

The end time of the subscription. This time can be in the past or future, and must be after the start_time.

None
rrule Optional[str]

The recurrence rule, given in iCalendar RFC 5545 format. Only monthly recurrences are supported at this time.

None
publishing_stages Optional[Sequence[Literal['preview', 'standard', 'finalized']]]

A sequence of one or more of the values "preview", "standard", or "finalized".

None
time_range_type Optional[Literal['acquired', 'published']]

"acquired" (new in 2.1.0) or "published".

None
geometry_relation Optional[Literal['intersects', 'contains', 'within']]

The relationship between the subscription geometry and the item geometry. 'intersects' (default): Returns items whose footprint geometry partially or fully overlaps with the subscription geometry. 'contains': Returns items where the footprint geometry fully encloses the AOI. 'within': Returns items whose entire footprint geometry is fully contained within the AOI.

None

Returns:

Type Description
dict

a representation of a subscription source.

Exceptions:

Type Description
ClientError

if a source can not be configured.

Examples:

source = catalog_source(
    ["PSScene"],
    ["ortho_analytic_4b"],
    geometry={
        "type": "Polygon",
        "coordinates": [
            [
                [37.791595458984375, 14.84923123791421],
                [37.90214538574219, 14.84923123791421],
                [37.90214538574219, 14.945448293647944],
                [37.791595458984375, 14.945448293647944],
                [37.791595458984375, 14.84923123791421],
            ]
        ],
    },
    start_time=datetime(2021, 3, 1),
    publishing_stages=["standard"],
    time_range_type="acquired",
)

request = build_request("Standard PSScene Ortho Analytic", source=source, delivery={})

cloud_filter_tool(clear_percent=None, cloud_percent=None, shadow_percent=None, heavy_haze_percent=None, light_haze_percent=None, snow_ice_percent=None)

Specify a subscriptions API cloud_filter tool.

The cloud_filter tool filters imagery after the clip tool has run and certain metadata values have been updated to pertain to the clip AOI. This tool offers a more detailed filtering of cloudy imagery than what can be achieved using only catalog source filters. For instance, you might want to receive only images that, after clipping, have a cloud_percent value of less than or equal to 25%.

Parameters:

Name Type Description Default
clear_percent Optional[planet.subscription_request.FilterValue]

Filters for images based on the percentage of clear sky.

None
cloud_percent Optional[planet.subscription_request.FilterValue]

Filters for images based on the percentage of cloud cover.

None
shadow_percent Optional[planet.subscription_request.FilterValue]

Filters for images based on the percentage of shadow cover.

None
heavy_haze_percent Optional[planet.subscription_request.FilterValue]

Filters for images based on the percentage of heavy haze cover.

None
light_haze_percent Optional[planet.subscription_request.FilterValue]

Filters for images based on the percentage of light haze cover.

None
snow_ice_percent Optional[planet.subscription_request.FilterValue]

Filters for images based on the percentage of snow or ice cover.

None

default_destination(path_prefix=None)

Specify the organization's default Destinations API destination.

Parameters:

Name Type Description Default
path_prefix Optional[str]

Path prefix for deliveries.

None

destination(destination_ref, path_prefix=None)

Specify a Destinations API destination by its ref.

Parameters:

Name Type Description Default
destination_ref str

The ID of the destination to deliver to.

required
path_prefix Optional[str]

Path prefix for deliveries.

None

file_format_tool(file_format)

Specify a subscriptions API file format tool.

Parameters:

Name Type Description Default
file_format str

The format of the tool output. Either "COG" or "PL_NITF".

required

Exceptions:

Type Description
planet.exceptions.ClientError

If file_format is not valid.

google_cloud_storage(credentials, bucket, path_prefix=None)

Delivery to Google Cloud Storage.

Parameters:

Name Type Description Default
credentials str

JSON-string of service account for bucket.

required
bucket str

GCS bucket name.

required
path_prefix Optional[str]

Path prefix for deliveries.

None

google_earth_engine(project, collection, credentials)

Delivery to Google Earth Engine.

Parameters:

Name Type Description Default
project str

GEE project name.

required
collection str

GEE Image Collection name.

required
credentials str

GEE service account credentials.

required

harmonize_tool(target_sensor)

Specify a subscriptions API harmonize tool.

Each sensor value transforms items captured by a defined set of instrument IDs. Items which have not been captured by that defined set of instrument IDs are unaffected by (passed through) the harmonization operation.

Parameters:

Name Type Description Default
target_sensor str

A value indicating to what sensor the input asset types should be calibrated.

required

Exceptions:

Type Description
planet.exceptions.ClientError

If target_sensor is not valid.

notifications(url, topics)

Specify a subscriptions API notification.

Webhook notifications proactively notify you when a subscription matches and delivers an item so you have confidence that you have all the expected imagery.

Parameters:

Name Type Description Default
url str

location of webhook/callback where you expect to receive updates.

required
topics List[str]

Event types that you can choose to be notified about.

required

oracle_cloud_storage(customer_access_key_id, customer_secret_key, bucket, region, namespace, path_prefix=None)

Delivery to Oracle Cloud Storage.

Parameters:

Name Type Description Default
customer_access_key_id str

Customer Secret Key credentials.

required
customer_secret_key str

Customer Secret Key credentials.

required
bucket str

The name of the bucket that will receive the subscription output.

required
region str

The region where the bucket lives in Oracle.

required
namespace str

Object Storage namespace name.

required
path_prefix Optional[str]

Path prefix for deliveries.

None

reproject_tool(projection, resolution=None, kernel='near')

Specify a subscriptions API reproject tool.

Parameters:

Name Type Description Default
projection str

A coordinate system in the form EPSG:n (for example, EPSG:4326 for WGS84, EPSG:32611 for UTM 11 North (WGS84), or EPSG:3857 for Web Mercator). Well known text CRS values are also supported (for example, WGS84).

required
resolution Optional[float]

The pixel width and height in the output file. If not provided, the default is the resolution of the input item. This value is in meters unless the coordinate system is geographic (such as EPSG:4326), in which case, it is pixel size in decimal degrees.

None
kernel str

The resampling kernel used. UDM files always use "near".

'near'

Exceptions:

Type Description
planet.exceptions.ClientError

If kernel is not valid.

s3_compatible(endpoint, bucket, region, access_key_id, secret_access_key, use_path_style=False, path_prefix=None)

S3 Compatible configuration.

Parameters:

Name Type Description Default
endpoint str

S3 compatible endpoint.

required
bucket str

S3-compatible bucket that will receive the subscription output.

required
region str

Region where the bucket lives in the s3 compatible service.

required
access_key_id str

Access key for authentication.

required
secret_access_key str

Secret key for authentication.

required
use_path_style bool

Use path-style addressing with bucket name in URL (default is False).

False
path_prefix Optional[str]

Custom string to prepend to the files delivered to the bucket. A slash (/) character will be treated as a "folder". Any other characters will be added as a prefix to the files.

None

sentinel_hub(collection_id, create_configuration=False)

Specify a Sentinel Hub hosting destination.

Requires the user to have a Sentinel Hub account linked with their Planet account. Subscriptions API will create a new collection to deliver data to if collection_id is omitted from the request. Will also create a new layer configuration for the collection if create_configuration is True. collection_id and create_configuration are mutually exclusive in the API.

Parameters:

Name Type Description Default
collection_id Optional[str]

Sentinel Hub collection

required
create_configuration Optional[bool]

Automatically create a layer configuration for your collection.

False

subscription_source(source_id, geometry, start_time, end_time=None)

Construct a subscription source.

See Subscribing to Planetary Variables and Analysis Ready sources or the OpenAPI spec to learn more about different product options.

The return value can be passed to planet.subscription_request.build_request.

Note: this function does not validate variable types and ids.

Parameters:

Name Type Description Default
source_id str

A source ID. See documenation for all available IDs.

required
geometry Union[dict, str]

The area of interest of the subscription that will be used to determine matches. May be a geojson-like dict or a Features API geometry reference (string)

required
start_time datetime

The start time of the subscription. This time can be in the past or future.

required
end_time Optional[datetime.datetime]

The end time of the subscription. This time can be in the past or future, and must be after the start_time.

None

Returns:

Type Description
dict

a representation of a subscription source.

Exceptions:

Type Description
ClientError

if a source can not be configured.

Examples:

pv_source = subscription_source(
    "SWC-AMSR2-C_V1.0_100",
    geometry={
        "type": "Polygon",
        "coordinates": [
            [
                [37.791595458984375, 14.84923123791421],
                [37.90214538574219, 14.84923123791421],
                [37.90214538574219, 14.945448293647944],
                [37.791595458984375, 14.945448293647944],
                [37.791595458984375, 14.84923123791421],
            ]
        ],
    },
    start_time=datetime(2021, 3, 1),
)

request = build_request(
    "soil_water_subscription",
    source=pv_source,
    delivery={},
)

toar_tool(scale_factor=10000)

Specify a subscriptions API reproject tool.

The toar tool supports the analytic asset type for PSScene and REOrthoTile item types. In addition to the analytic asset, the corresponding XML metadata asset type is required.

Parameters:

Name Type Description Default
scale_factor int

Scale factor applied to convert 0.0 to 1.0 reflectance floating point values to a value that fits in 16bit integer pixels. The API default is 10000. Values over 65535 could result in high reflectances not fitting in 16bit integers.

10000

reporting

Functionality for reporting progress.

AssetStatusBar (ProgressBar)

Bar reporter of asset status.

__init__(self, item_type, item_id, asset_type, disable=False) special

Initialize the object.

open_bar(self)

Initialize and start the progress bar.

ProgressBar

Abstract base class for progress bar reporters.

open_bar(self)

Initialize and start the progress bar.

StateBar (ProgressBar)

Bar reporter of order state.

Examples:

from planet import reporting

with reporting.StateBar(state='creating') as bar:
    bar.update(state='created', order_id='oid')
    ...

__init__(self, order_id=None, state=None, disable=False) special

Initialize the object.

Parameters:

Name Type Description Default
order_id Optional[str]

Id of the order.

None
state Optional[str]

State of the order.

None

open_bar(self)

Initialize and start the progress bar.

update_state(self, state)

Simple function to be used as a callback for state reporting

DestinationsClient (_BaseClient)

Asynchronous Destinations API client.

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         cl = sess.client('destinations')
...         # use client here
...
>>> asyncio.run(main())

__init__(self, session, base_url=None) special

Parameters:

Name Type Description Default
session Session

Open session connected to server.

required
base_url Optional[str]

The base URL to use. Defaults to production destinations API base url.

None

create_destination(self, request) async

Create a new destination.

Parameters:

Name Type Description Default
request dict

Destination content to create, all attributes are required.

required

Returns:

Type Description
dict

A dictionary containing the created destination details.

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

get_default_destination(self) async

Get the current default destination. The default destination is globally available to all members of an organization.

Returns:

Type Description
dict

A dictionary containing the default destination details.

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

get_destination(self, destination_id) async

Get a specific destination by its ID.

Parameters:

Name Type Description Default
destination_id str

The ID of the destination to retrieve.

required

Returns:

Type Description
dict

A dictionary containing the destination details.

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

list_destinations(self, archived=None, is_owner=None, can_write=None, is_default=None) async

List all destinations. By default, all non-archived destinations in the requesting user's org are returned.

Parameters:

Name Type Description Default
archived bool

If True, include archived destinations.

None
is_owner bool

If True, include only destinations owned by the requesting user.

None
can_write bool

If True, include only destinations the requesting user can modify.

None
is_default bool

If True, include only the default destination.

None

Returns:

Type Description
dict

A dictionary containing the list of destinations inside the 'destinations' key.

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

patch_destination(self, destination_id, request) async

Update a specific destination by its ID.

Parameters:

Name Type Description Default
destination_id str

The ID of the destination to update.

required
request dict

Destination content to update, only attributes to update are required.

required

Returns:

Type Description
dict

A dictionary containing the updated destination details.

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

set_default_destination(self, destination_id) async

Set an existing destination as the default destination. Default destinations are globally available to all members of an organization. An organization can have zero or one default destination at any time. Ability to set a default destination is restricted to organization administrators and destination owners.

Parameters:

Name Type Description Default
destination_id str

The ID of the destination to set as default.

required

Returns:

Type Description
dict

A dictionary containing the default destination details.

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

unset_default_destination(self) async

Unset the current default destination. Ability to unset a default destination is restricted to organization administrators and destination owners. Returns None (HTTP 204, No Content) on success.

Returns:

Type Description
None

None

Exceptions:

Type Description
APIError

If the API returns an error response.

ClientError

If there is an issue with the client request.

FeaturesClient (_BaseClient)

Asyncronous Features API client

For more information about the Features API, see the documentation at https://docs.planet.com/develop/apis/features/

Examples:

>>> import asyncio
>>> from planet import Session
>>>
>>> async def main():
...     async with Session() as sess:
...         cl = sess.client('features')
...         # use client here
...
>>> asyncio.run(main())

__init__(self, session, base_url=None) special

Parameters:

Name Type Description Default
session Session

Open session connected to server.

required
base_url Optional[str]

The base URL to use. Defaults to the Features API base url at api.planet.com.

None

add_items(self, collection_id, feature, property_id=None) async

Add a Feature or FeatureCollection to the collection given by collection_id. Returns a list of feature references.

Features API only accepts Polygon and MultiPolygon.

collection_id: the collection to add the feature to feature: a dict containing a geojson Feature or FeatureCollection, or an instance of a class that implements geo_interface (e.g. a Shapely or GeoPandas geometry object) property_id (optional): the name of a property in the properties block of the supplied feature(s). The value will become the feature's id.

When the feature is added to the collection, it will be given an ID. The ID can be overriden by providing an id in the feature's properties. Title and description can also be set this way using the title and description properties.

Examples:

new_features = await features_client.add_features(
  collection_id="my-collection",
  feature=feature,
)

note: if a geojson Geometry is supplied, it will be converted to a Feature. However, we recommend doing this conversion yourself so that you can set a title and description property.

The return value is always an iterator, even if you only upload one feature.

create_collection(self, title, description=None) async

Create a new collection with the given title and description, returning the collection id.

Examples:

collection_id = await features_client.create_collection(
  title="My Collection",
  description="a test collection"
)

delete_collection(self, collection_id) async

Delete a collection.

Parameters:

Name Type Description Default
collection_id str

The ID of the collection to delete

required

Examples:

await features_client.delete_collection(
    collection_id="my-collection"
)

delete_item(self, collection_id, feature_id) async

Delete a feature from a collection.

Parameters:

Name Type Description Default
collection_id str

The ID of the collection containing the feature

required
feature_id str

The ID of the feature to delete

required

Examples:

await features_client.delete_item(
    collection_id="my-collection",
    feature_id="feature-123"
)

get_collection(self, collection_id) async

Get collection metadata.

note: when looking up or adding features to a collection, you can pass the collection ID directly to the add_features or list_features methods. It is not necessary to look up the collection metadata first.

get_item(self, collection_id, feature_id) async

Return metadata for a single feature in a collection

list_collections(self, limit=0)

List the feature collections you have access to.

Examples:

collections = await client.list_collections()
async for collection in collections:
    print(collection)

list_items(self, collection_id, limit=10)

List features in collection_id.

Returns an iterator of Features, which are dict instances with a convenience method/property for getting a feature reference (.ref). The reference can be used in the Data, Orders and Subscriptions APIs. Within the Python SDK, the entire Feature can generally be passed to functions that accept a geometry.

Examples:

results = await client.list_items(collection_id)
async for feature in results:
    print(feature.ref)
    print(feature["id"])
    print(feature["geometry"])

Planet

Planet API client. This client contains non-async methods.

Authentication is required: defaults to detecting API key from environment (PL_API_KEY).

Members:

  • data: for interacting with the Planet Data API.
  • destinations: Destinations API.
  • orders: Orders API.
  • subscriptions: Subscriptions API.
  • features: Features API

Quick start example:

# requires PL_API_KEY

pl = Planet()
for item in pl.data.search(['PSScene'], limit=5):
    print(item)

for sub in pl.subscriptions.list_subscriptions():
    print(item)

Parameters:

Name Type Description Default
session Optional[planet.http.Session]

Optional Session. The Session can be provided allowing for customization, and will default to standard behavior when not provided.

None
base_url Optional[str]

Optional base URL for Planet APIs. Defaults to (https://api.planet.com). Each API will append its specific path suffix (/data/v1, /compute/ops, etc.).

None
Back to top