Skip to content

Responses

OpenAQ python returns API responses as deserialized objects with helper methods to serialize the results to JSON.

Base Response Class

All response classes share some convenience methods for deserializing and serializing the response contents.

Base clase for all reponse classes.

Handles serialization and deserialization of JSON data and setting of class attributes

Source code in openaq/shared/responses.py
class _ResponseBase:
    """Base clase for all reponse classes.

    Handles serialization and deserialization of JSON data and setting of
    class attributes
    """

    @classmethod
    def _deserialize(cls, data: Mapping):
        """Deserializes data and convert keys from camel case to snake case.

        Args:
            data: input dictionary of API response data to be deserialized.
        """
        out = {}
        for k, v in data.items():
            if isinstance(v, dict):
                out[decamelize(k)] = cls._deserialize(v)
            if isinstance(v, list):
                out[decamelize(k)] = []
                for x in v:
                    if isinstance(x, dict):
                        out[decamelize(k)].append(cls._deserialize(x))
                    else:
                        out[decamelize(k)].append(x)
            else:
                out[decamelize(k)] = v
        return out

    def _serialize(self, data: Mapping):
        """Serializes data and convert keys to camel case.

        Args:
            data: input dictionary of API response data to be serialized.
        """
        if isinstance(data, list):
            return [
                self._serialize(i) if isinstance(i, (Mapping, list)) else i
                for i in data
            ]
        return {
            camelize(k): self._serialize(v) if isinstance(v, (Mapping, list)) else v
            for k, v in data.items()
        }

    @classmethod
    def load(cls, data: Mapping) -> _ResponseBase:
        """Deserializes JSON response from API into response object.

        Args:
            data: A dictionary representation of the data returned from the API.

        Returns:
            Deserialized representation of the response data as a Python object.
        """
        deserialized_data = cls._deserialize(data)

        # Filter out fields that are not in the class annotations
        expected_fields = {
            k: v for k, v in deserialized_data.items() if k in cls.__annotations__
        }
        return cls(**expected_fields)

    def dict(self) -> Dict:
        """Serializes response data to Python dictionary.

        Returns:
            Python dictionary of the response data.
        """
        return asdict(self)

    def json(self, encoder: ModuleType = json) -> str:
        """Serializes response data to JSON string.

        Allows for setting encoder module. Defaults to python core `json`, `orjson` also supported with optional install `pip install openaq[orjson]`

        Args:
            encoder: JSON serializer module.

        Returns:
            string representation of the response in JSON.
        """
        if encoder == orjson:
            assert orjson is not None, "orjson must be installed."
        return encoder.dumps(self._serialize(self.dict()), ensure_ascii=False)

dict()

Serializes response data to Python dictionary.

Returns:

Type Description
Dict

Python dictionary of the response data.

Source code in openaq/shared/responses.py
def dict(self) -> Dict:
    """Serializes response data to Python dictionary.

    Returns:
        Python dictionary of the response data.
    """
    return asdict(self)

json(encoder=json)

Serializes response data to JSON string.

Allows for setting encoder module. Defaults to python core json, orjson also supported with optional install pip install openaq[orjson]

Parameters:

Name Type Description Default
encoder ModuleType

JSON serializer module.

json

Returns:

Type Description
str

string representation of the response in JSON.

Source code in openaq/shared/responses.py
def json(self, encoder: ModuleType = json) -> str:
    """Serializes response data to JSON string.

    Allows for setting encoder module. Defaults to python core `json`, `orjson` also supported with optional install `pip install openaq[orjson]`

    Args:
        encoder: JSON serializer module.

    Returns:
        string representation of the response in JSON.
    """
    if encoder == orjson:
        assert orjson is not None, "orjson must be installed."
    return encoder.dumps(self._serialize(self.dict()), ensure_ascii=False)

load(data) classmethod

Deserializes JSON response from API into response object.

Parameters:

Name Type Description Default
data Mapping

A dictionary representation of the data returned from the API.

required

Returns:

Type Description
_ResponseBase

Deserialized representation of the response data as a Python object.

Source code in openaq/shared/responses.py
@classmethod
def load(cls, data: Mapping) -> _ResponseBase:
    """Deserializes JSON response from API into response object.

    Args:
        data: A dictionary representation of the data returned from the API.

    Returns:
        Deserialized representation of the response data as a Python object.
    """
    deserialized_data = cls._deserialize(data)

    # Filter out fields that are not in the class annotations
    expected_fields = {
        k: v for k, v in deserialized_data.items() if k in cls.__annotations__
    }
    return cls(**expected_fields)

Resources

CountryBase

Base representation for country resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for country

code str

ISO 3166-1 alpha-2 2 letter country code

name str

country name

Country

Representation of country resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for country

code str

ISO 3166-1 alpha-2 2 letter country code

name str

name of country

datetime_first str

datetime of first measurement available.

datetime_last str

datetime of last measurement available.

parameters List[ParameterBase]

list of parameters available in the country.

InstrumentBase

Base representation for instrument resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for instrument

name str

instrument name

Instrument

Representation of instrument resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for instrument

name str

name of instrument

is_monitor bool

boolean indicating if instrument is graded as reference monitor.

manufacturer ManufacturerBase

instrument manufacturer

ManufacturerBase

Base representation for manufacturer resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for manufacturer

name str

manufacturer name

Manufacturer

Representation of manufacturer resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for manufacturer

name str

manufacturer name

instruments List[InstrumentBase]

a list of instruments made by the manufacturer

Measurement

Representation of measurement resource in OpenAQ.

Attributes:

Name Type Description
period Period

period object

value float

measured value or mean value if aggregate to period.

parameter ParameterBase

parameter object

coordinates Union[Coordinates, None]

WGS84 coordinate values if location is mobile.

summary Summary

summary object

coverage Coverage

coverage object

Period

Representation of a measurement time period.

Attributes:

Name Type Description
label str

label of measurement period

interval str

time interval of measurement aggregation

datetime_from Datetime

datetime object of period start

datetime_to Datetime

datetime object of period end

Summary

Statistical summary of measurement values.

Attributes:

Name Type Description
min float

mininum value

q02 float

2nd percentile

q25 float

25th percentile

median float

median value i.e. 50th percentile

q75 float

75th percentile

q98 float

98th percentile

max float

maximum value

sd float

standard deviation

OwnerBase

Base representation for owner resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for owner

name str

owner name

Owner

Detailed information about an owner in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for owner

name str

owner name

ParameterBase

Base representation for measurement parameter resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for parameter

name str

parameter name

Parameter

Representation of parameter resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for parameter

name str

name of parameter

units str

units of measurement of parameter

display_name Union[str, None]

display name of parameter

description Union[str, None]

description of parameter

ProviderBase

Base representation for providers in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for provider

name str

provider name

Provider

Representation of provider resource in OpenAQ.

id: unique identifier for provider name: provider name source_name: name of source export_prefix: license: data license of provider datetime_added: ISO-8601 datetime of when provider was added to OpenAQ datetime_first: ISO-8601 datetime of first measurement datetime_last: ISO-8601 datetime of first measurement owner_entity: owner entity object parameters: list of parameters available from provider bbox: bounding box of geographic area of provider locations

SensorBase

Base representation for sensor resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for sensor

name str

sensor name

parameter ParameterBase

parameter measured by sensor

Coordinates

Representation for geographic coordinates in OpenAQ.

coordinates are represented in WGS84 (AKA EPSG 4326) coordinate system.

Attributes:

Name Type Description
latitude float

WGS84 latitude coordinate value

longitude float

WGS84 longitude coordinate value

Datetime

Representation for timestamps in OpenAQ.

Attributes:

Name Type Description
utc str

ISO-8601 formatted datetime value at UTC

local str

ISO-8601 formatted datetime value at local timezone offset

OwnerEntity

Representation of owner entitiy resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for owner entity

name str

owner entity name

Location

Representation of location resource in OpenAQ.

Attributes:

Name Type Description
id int

unique location identifier

name str

location name

locality Union[str, None]

name of locality

timezone str

timezone of location

country CountryBase

country base object with country information

owner OwnerBase

owner object

provider ProviderBase

provider object

is_mobile bool

boolean indicating whether or not location is mobile (true) or stationary (false)

is_monitor bool

boolean indicating whether or not location is a reference monitor (true) or air sensor (false)

instruments List[InstrumentBase]

list of instruments used by locaiton node

sensors List[SensorBase]

list of sensors used by location node

coordinates Coordinates

coordinates objects with latitude and longitude of location

bounds Tuple[float, float, float, float]

WGS84 geographic bounds of location

distance Union[float, None]

distance from coordinates value when querying by radius and coordinates

datetime_first Datetime

ISO 8601 datetime of first measurement for location

datetime_last Datetime

ISO 8601 datetime of last measurement for location

API Responses

Meta

API response metadata.

Attributes:

Name Type Description
name str

API name

website str

API URL

page int

the page number for paginated results.

limit int

the limit number of records per page.

found int

a count of the total number of records.

CountriesResponse

Representation of the API response for countries resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Country]

a list of country records.

InstrumentsResponse

Representation of the API response for instruments resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Instrument]

a list of instrument records.

LocationsResponse

Representation of the API response for locations resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Location]

a list of location records.

ManufacturersResponse

Representation of the API response for manufacturers resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Manufacturer]

a list of manufacturer records.

MeasurementsResponse

Representation of the API response for measurements resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Measurement]

a list of measurement records.

OwnersResponse

Representation of the API response for owners resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Owner]

a list of owner records.

ParametersResponse

Representation of the API response for parameters resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Parameter]

a list of parameter records.

ProvidersResponse

Representation of the API response for providers resource.

Attributes:

Name Type Description
meta Meta

a metadata object containing information about the results.

results List[Provider]

a list of provider records.