$PRECONNECT_LINK $PRECONNECT_LINK $PRECONNECT_LINK $PRECONNECT_LINK
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 response classes.

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

Attributes:

Name Type Description
headers Headers
meta Meta
Source code in openaq/shared/responses.py
@dataclass
class _ResponseBase:
    """Base clase for all response classes.

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

    Attributes:
        headers:
        meta:
    """

    headers: Headers
    meta: Meta
    results: List[Any]

    @classmethod
    def read_response(cls, response: Response):
        valid_headers = [field.name for field in fields(Headers)]
        return cls(
            Headers(
                **{
                    k.replace('-', '_'): v
                    for k, v in response.headers.items()
                    if k.replace('-', '_') in valid_headers
                }
            ),
            response.json()['meta'],
            response.json()['results'],
        )

    def __post_init__(self):
        """Sets class attributes to correct type after checking input type."""
        if isinstance(self.meta, dict):
            self.meta = Meta.load(self.meta)

    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()
        }

    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)

__post_init__()

Sets class attributes to correct type after checking input type.

Source code in openaq/shared/responses.py
def __post_init__(self):
    """Sets class attributes to correct type after checking input type."""
    if isinstance(self.meta, dict):
        self.meta = Meta.load(self.meta)

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)

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

object detailing the measurement period.

value float

measured value or mean value if aggregate to period.

parameter ParameterBase

object representing the parameter measured by the sensor.

coordinates Union[Coordinates, None]

WGS84 coordinate values if location is mobile.

coverage Coverage

object detailing the data coverage of the sensor for the period.

summary Summary

object with summary statistics of mueasurment values of the sensor for the period.

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/50th percentile

q75 float

75th percentile

q98 float

98th percentile

max float

maximum value

sd Union[float, None]

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: 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 entities_id: entity id 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

Sensor

Detailed information about a sensor in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for sensor

name str

sensor name

parameter Parameter

object representing the parameter measured by the sensor.

datetime_first Union[Datetime, None]

datetime value representing first value available for the sensor.

datetime_last Union[Datetime, None]

datetime value representing last value available for the sensor.

coverage Union[Coverage, None]

object detailing the data coverage of the sensor

latest Union[LatestBase, None]

latest measurement value for the sensor

summary Union[Summary, None]

object with summary statistics of mueasurment values for the 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

object with information about the location owner

provider ProviderBase

object with information about the location provider

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

License

Representation of license resource in OpenAQ.

Attributes:

Name Type Description
id int

unique identifier for license

name str

name of license

commercial_use_allowed bool

boolean indicating if commercial use is allowed

attribution_required bool

boolean indicating if attribution is required

share_alike_required bool

boolean indicating if share alike is required

modification_allowed bool

boolean indicating if modification is allowed

redistribution_allowed bool

boolean indicating if redistribution is allowed

source_url Union[str, None]

URL of original source of license

API Responses

Headers

API response headers.

Attributes:

Name Type Description
x_ratelimit_limit int

The X-RateLimit-Limit header indicates the maximum number of requests for rate limit policy

x_ratelimit_remaining int

The X-RateLimit-Remaining header indicates the remaining number of requests for the period

x_ratelimit_used int

The X-RateLimit-Remaining header indicates the number of requests used for the period

x_ratelimit_reset int

The X-RateLimit-Reset header indicates when, in number of seconds, the rate limit period resets

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

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

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
headers

a Headers object of response headers

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

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

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

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

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

a metadata object containing information about the results.

results List[Provider]

a list of provider records.

LicensesResponse

Representation of the API response for licenses resource.

Attributes:

Name Type Description
meta

a metadata object containing information about the results.

results List[License]

a list of license records.

SensorsResponse

Representation of the API response for sensors resource.

Attributes:

Name Type Description
meta

a metadata object containing information about the results.

results List[Sensor]

a list of sensor records.

$PRECONNECT_LINK $PRECONNECT_LINK
$PRECONNECT_LINK $PRECONNECT_LINK