Tasking API Order Edit and Cancellation


Introduction


This tutorial is an introduction on how to edit and cancel tasking orders using Planet's Tasking API. It provides code samples on how to write simple Python code to do this.

The API reference documentation can be found at https://developers.planet.com/docs/tasking

Requirements


Software & Modules

This tutorial assumes familiarity with the Python programming language throughout. Familiarity with basic REST API concepts and usage is also assumed.

We'll be using a "Jupyter Notebook" (aka Python Notebook) to run through the examples. To learn more about and get started with using Jupyter, visit: Jupyter and IPython.

For the best experience, download this notebook and run it on your system, and make sure to install the modules listed below first. You can also copy the examples' code to a separate Python files an run them directly with Python on your system if you prefer.

Planet API Key

You should have an account on the Planet Platform to access the Tasking API. You may retrieve your API key from your account page, or from the "API Tab" in Planet Explorer.

Before continuing

It is highly recommended that before continuing with these examples you first complete the Tasking API Order Creation Notebook, which will give instructions on how to first create a tasking order. We will be creating a tasking order as part of this notebook but will not be going into details.

Overview


The basic workflow

  1. Create the tasking order
  2. Edit the tasking order
  3. Cancel the tasking order

Examples on how to create tasking orders and view their captures can be found in the notebook planet_tasking_api_order_creation.ipynb

API Endpoints

This tutorial will cover the following API endpoint:

Basic Setup


Before interacting with the Planet Tasking API using Python, we will set up our environment with some useful modules and helper functions.

  • We'll configure authentication to the Planet Tasking API
  • We'll use the requests Python module to make HTTP communication easier.
  • We'll use the json Python module to help us work with JSON responses from the API.
  • We'll use the pytz Python module to define the time frame for the order that we will be creating.
  • We'll create a function called p that will print Python dictionaries nicely.

Then we'll be ready to make our first call to the Planet Tasking API by hitting the base endpoint at https://api.planet.com/tasking/v2.

Let's start by configuring authentication:

Authentication

Authentication with the Planet Tasking API can be achieved using a valid Planet API key.

You can export your API Key as an environment variable on your system:

export PL_API_KEY="YOUR API KEY HERE"

Or add the variable to your path, etc.

To start our Python code, we'll setup an API Key variable from an environment variable to use with our requests:


In [ ]:
# Import the os module in order to access environment variables
import os

#If you are running this notebook outside of the docker environment that comes with the repo, you can uncomment the next line to provide your API key
#os.environ['PL_API_KEY']=input('Please provide your API Key')

# Setup the API Key from the `PL_API_KEY` environment variable
PLANET_API_KEY = os.getenv('PL_API_KEY')

Helper Modules and Functions


In [ ]:
# Import helper modules
import json
import requests
import pytz
from time import sleep
from datetime import datetime, timedelta

In [ ]:
# Helper function to printformatted JSON using the json module
def p(data):
    print(json.dumps(data, indent=2))

In [ ]:
# Setup Planet Tasking PLANET_API_HOST
TASKING_ORDERS_API_URL = "https://api.planet.com/tasking/v2/orders/"

# Setup the session
session = requests.Session()

# Authenticate
session.headers.update({
    'Authorization': f'api-key {PLANET_API_KEY}',
    'Content-Type': 'application/json'
})

1 | Creating an order


In [ ]:
# Define the name and coordinates for the order
name=input("Give the order a name")
latitude=float(input("Provide the latitude"))
longitude=float(input("Provide the longitude"))

# Because the geometry is GeoJSON, the coordinates must be longitude,latitude
order = {
    'name': name,
    'geometry': {
        'type': 'Point',
        'coordinates': [
            longitude,
            latitude
        ]
    }
}

# Set a start and end time, giving the order a week to complete
tomorrow = datetime.now(pytz.utc) + timedelta(days=1)
one_week_later = tomorrow + timedelta(days=7)

datetime_parameters = {
    'start_time': tomorrow.isoformat(),
    'end_time': one_week_later.isoformat()
}

# Add use datetime parameters
order.update(datetime_parameters)

In [ ]:
# The creation of an order is a POST request to the /orders endpoint
res = session.request('POST', TASKING_ORDERS_API_URL, json=order)

if response.status_code == 403:
    print('Your PLANET_API_KEY is valid, but you are not authorized.')
elif response.status_code == 401:
    print('Your PLANET_API_KEY is incorrect')
elif response.status_code == 201:
    print('Your order was created successfully')
else:
    print(f'Received status code {res.status_code} from the API. Please contact support.')

# Order created. Here is the response
p(res.json())

2 | Editing the tasking order

Changing the tasking order that we have just created is possible but with a few restrictions that you need to be aware of. Only the name, the rank, the start time and the end time of a tasking order can be changed. The geometry of an existing tasking order cannot be altered after creation. If the geometry is wrong, then the only recourse is to cancel the tasking order and start anew.

With editing, the "when can a tasking order be edited" is just as important as the "what can be edited". A tasking order can have the following states: PENDING, REQUESTED, IN PROGRESS, FULFILLED, CANCELLED and EXPIRED. A tasking order can only be edited in the first three states, PENDING, REQUESTED and IN PROGRESS and of these states, the start time of a tasking order can only be edited whilst the tasking order is in PENDING or REQUESTED. The start time cannot be changed once a tasking order is in progress.kwargs

With that, let's look at editing the order that we just created to give it a different name:


In [ ]:
# Get the response JSON and extract the ID of the order
response = res.json()
order_id = response["id"]

# Provide a new name for the order
new_name=input("Provide a new name for the order")

# Define the payload
edit_payload = {
    'name': new_name
}

In [ ]:
# Editing an order requires a PUT request to be made. The order id is concantenated to the end of the URl. E.g. https://api.planet.com/tasking/v2/orders/<ORDER_ID>
res = session.request('PUT', TASKING_ORDERS_API_URL + order_id, json=edit_payload)

p(res.json())

3 | Cancelling the tasking order

As with editing a tasking order, cancellation has some limitations on when a tasking order can be cancelled. Tasking orders can only be cancelled only when the tasking order is in one of the following states: PENDING, IN PROGRESS, RECEIVED and REQUESTED.

Let's delete the tasking order that we have created:


In [ ]:
# Get the response JSON and extract the ID of the order
response = res.json()
order_id = response["id"]

# Cancel an order by sending a DELETE request to the orders endpoint
res = session.request('DELETE', TASKING_ORDERS_API_URL + order_id)

p(res.json())