Adding New and Custom Extensions#

This tutorial will cover using the PropertiesExtension and ExtensionManagementMixin classes in pystac.extensions.base to implement a new extension to PySTAC.

For this exercise, we will implement an imaginary Order Request Extension that allows us to track an internal order ID associated with a given satellite image, as well as the history of that imagery order. This use-case is specific enough that it would probably not be a good candidate for an actual STAC Extension, but it gives us an opportunity to highlight some of the key aspects and patterns used in implementing STAC Extensions in PySTAC.

First, we import the PySTAC modules and classes that we will be using throughout the tutorial.

from datetime import datetime, timedelta
from pprint import pprint
from typing import Any, Dict, List, Optional, Union
from uuid import uuid4

import pystac
from pystac.utils import (
from pystac.extensions.base import (

Define the Extension#

Our extension will extend STAC Items by adding the following properties:

  • order:id: A unique string ID associated with the internal order for this image. This field will be required.

  • order:history: A chronological list of events associated with this order. Each of these “events” will have a timestamp and an event type, which will be one of the following: submitted, started_processing, delivered, cancelled. This field will be optional.

Create Extension Classes#

Let’s start by creating a class to represent the order history events.

class OrderEventType(StringEnum):
    SUBMITTED = "submitted"
    STARTED_PROCESSING = "started_processing"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"

class OrderEvent:
    properties: Dict[str, Any]

    def __init__(self, properties: Dict[str, Any]) -> None: = properties

    def event_type(self) -> OrderEventType:
        return get_required(

    def event_type(self, v: OrderEventType) -> None:["type"] = str(v)

    def timestamp(self) -> datetime:
        return str_to_datetime(

    def timestamp(self, v: datetime) -> None:["timestamp"] = datetime_to_str(v)

    def __repr__(self) -> str:
        return "<OrderEvent " \
            f"type={self.event_type} " \

    def apply(
        event_type: OrderEventType,
        timestamp: datetime,
    ) -> None:
        self.event_type = event_type
        self.timestamp = timestamp

    def create(
        event_type: OrderEventType,
        timestamp: datetime,
    ) -> "OrderEvent":
        oe = cls({})
        return oe

    def to_dict(self) -> Dict[str, Any]:

A few important notes about how we constructed this:

  • We used PySTAC’s StringEnum class, which inherits from the Python Enum class, to capture the allowed event type values. This class has built-in methods that will convert these instances to strings when serializing STAC Items to JSON.

  • We use property getters and setters to manipulate a properties dictionary in our OrderEvent class. We will see later how this pattern allows us to mutate Item property dictionaries in-place so that updates to the OrderEvent object are synced to the Item they extend.

  • The timestamp property is converted to a string before it is saved in the properties dictionary. This ensures that dictionary is always JSON-serializable but allows us to work with the values as a Python datetime instance when using the property getter.

  • We use event_type as our property name so that we do not shadow the built-in type function in the apply method. However, this values is stored under the desired "type" key in the underlying properties dictionary.

Next, we will create a new class inheriting from PropertiesExtension and ExtensionManagementMixin. Since this class only extends pystac.Item instance, we do not need to make it generic. If you were creating an extension that applied to multiple object types (e.g. pystac.Item and pystac.Asset) then you would need to inherit from typing.Generic as well and create concrete extension classed for each of these object types (see the EOExtension, ItemEOExtension, and AssetEOExtension classes for an example of this implementation).

SCHEMA_URI: str = ""
PREFIX: str = "order:"
ID_PROP: str = PREFIX + "id"
HISTORY_PROP: str = PREFIX + "history"

class OrderExtension(
    ExtensionManagementMixin[Union[pystac.Item, pystac.Collection]]
    def __init__(self, item: pystac.Item):
        self.item = item =

    def apply(
        order_id: str = None,
        history: Optional[List[OrderEvent]] = None
    ) -> None:
        self.order_id = order_id
        self.history = history

    def order_id(self) -> str:
        return get_required(self._get_property(ID_PROP, str), self, ID_PROP)

    def order_id(self, v: str) -> None:
        self._set_property(ID_PROP, v, pop_if_none=False)

    def history(self) -> Optional[List[OrderEvent]]:
        return map_opt(
            lambda history: [OrderEvent(d) for d in history],
            self._get_property(HISTORY_PROP, List[OrderEvent])

    def history(self, v: Optional[List[OrderEvent]]) -> None:
            map_opt(lambda history: [event.to_dict() for event in history], v),

    def get_schema_uri(cls) -> str:
        return SCHEMA_URI

    def ext(cls, obj: pystac.Item, add_if_missing: bool = False) -> "OrderExtension":
        if isinstance(obj, pystac.Item):
            cls.validate_has_extension(obj, add_if_missing)
            return OrderExtension(obj)
            raise pystac.ExtensionTypeError(
                f"OrderExtension does not apply to type '{type(obj).__name__}'"

As with the OrderEvent class, we use property getters and setters for our extension fields (the PropertiesExtension class has a properties attribute where these are stored). Rather than setting these values directly in the dictionary, we use the _get_property and _set_property methods that are built into the PropertiesExtension class). We also add an ext method that will be used to extend pystac.Item instances, and a get_schema_uri method that is required for all PropertiesExtension classes.

Use the Extension#

Let’s try using our new classes to extend an Item and access the extension properties. We’ll start by loading the core Item example from the STAC spec examples here and printing the existing properties.

item = pystac.read_file('')

{'title': 'Core Item',
 'description': 'A sample STAC Item that includes examples of all common metadata',
 'datetime': None,
 'start_datetime': '2020-12-11T22:38:32.125Z',
 'end_datetime': '2020-12-11T22:38:32.327Z',
 'created': '2020-12-12T01:48:13.725Z',
 'updated': '2020-12-12T01:48:13.725Z',
 'platform': 'cool_sat1',
 'instruments': ['cool_sensor_v1'],
 'constellation': 'ion',
 'mission': 'collection 5624',
 'gsd': 0.512}

Next, let’s verify that this Item does not implement our new Order Extension yet and that it does not already contain any of our Order Extension properties.

print(f"Implements Extension: {OrderExtension.has_extension(item)}")
print(f"Order ID: {}")
for event in, []):
Implements Extension: False
Order ID: None

As expected, this Item does not implement the extension (i.e. the schema URI is not in the Item’s stac_extensions list). Let’s add it, create an instance of OrderExtension that extends the Item, and add some values for our extension fields.

order_ext = OrderExtension.ext(item, add_if_missing=True)

# Create a unique string ID for the order ID
order_ext.order_id = str(uuid4())

# Create some fake order history and set it using the extension
event_1 = OrderEvent.create(
    event_type=OrderEventType.SUBMITTED, - timedelta(days=1)
event_2 = OrderEvent.create(
    event_type=OrderEventType.STARTED_PROCESSING, - timedelta(hours=12)
event_3 = OrderEvent.create(
    event_type=OrderEventType.DELIVERED, - timedelta(hours=1)
order_ext.history = [event_1, event_2, event_3]

Now let’s check to see if these values were written to our Item properties.

print(f"Implements Extension: {OrderExtension.has_extension(item)}")
print(f"Order ID: {}")
for event in, []):
Implements Extension: True
Order ID: f6f367b6-a787-48de-941f-08a04be77683
{'timestamp': '2022-01-20T11:44:01.803820Z', 'type': 'submitted'}
{'timestamp': '2022-01-20T23:44:01.803939Z', 'type': 'started_processing'}
{'timestamp': '2022-01-21T10:44:01.803999Z', 'type': 'delivered'}
[ ]: