Create an instance of the client
OpenAQ Python provides a synchronous client via the OpenAQ
class and an
asynchronous client via the AsyncOpenAQ
class, for working with
async
/await
within event loops. This guide will show the options on how to
create an instance of the client class.
The OpenAQ API key can be passed directly as an argument on the creation of the
client as shown above. Alternatively, we can use the OPENAQ_API_KEY
environment
variable to set the api_key value without directly setting the value on client
instantiation. e.g.:
Where main.py
is something like:
Setting the API key via the client class argument on instantiation will also
supercede the implicit setting of api_key
through the OPENAQ_API_KEY
environment variable.
openaq
uses httpx under-the-hood to make http
calls to the OpenAQ API. The OpenAQ client follows the same pattern as
httpx for opening and closing connections. Once
the client is instantiated an httpx.Client
(or httpx.AsyncClient
) is opened
and must be explicitly closed after use. This allows for more efficient usage of
network resources by maintaining an open connection.
Alternatively, we can use a context manager to handle closing the connection for us:
API key
An API Key is required to make requests with the OpenAQ API.
We can add an API Key to OpenAQ Python one of two ways. As shown above, the API
key string can be directly passed when instantiating the OpenAQ
or
AsyncOpenAQ
class via the api_key
argument. Alternatively, if a key is not
passed to the constructor OpenAQ
and AsyncOpenAQ
will automatically look for
a system environment variable named OPENAQ-API-KEY
and set the value of that
to the api_key
argument. Directly passing a value to the api_key
argument in
the client constructors will always override an environment variable.