Getting started overview

Getting started with OpenAQ involves a sequence of steps to provision access and begin retrieving air quality data. The process begins with account registration, followed by the generation of an API key, which serves as the primary method for authenticating requests. Once an API key is obtained, developers can construct their first request to one of the available API endpoints, such as retrieving a list of locations or recent measurements. OpenAQ offers a Community Plan for non-commercial use, which provides an entry point for testing and development before scaling to commercial or higher-volume usage with paid plans.

The OpenAQ API is designed to aggregate and standardize air quality data from diverse sources globally, making it accessible for various applications, including academic research and public health initiatives (OpenAQ Homepage). This guide focuses on the technical steps required to initiate API interaction.

Quick Reference Guide

Step What to do Where
1. Sign Up Create an OpenAQ account. OpenAQ Billing Documentation
2. Get API Key Generate your API key from the dashboard. OpenAQ API Keys Guide
3. Make Request Construct and execute your first API call. OpenAQ API Reference
4. Explore Data Review available endpoints and parameters. OpenAQ API Endpoints

Create an account and get keys

To access the OpenAQ API, you must first register for an account. This process typically involves providing an email address and creating a password. Upon successful registration, you will gain access to the OpenAQ dashboard, where API keys are managed. The OpenAQ billing documentation outlines the different plans available, including the free Community Plan, and guides you through the signup process.

Generating an API Key

Once logged into your OpenAQ account, navigate to the API Keys section of your dashboard. Here, you will find an option to generate a new API key. It is crucial to securely store your API key, as it authenticates your requests and grants access to the data. Treat your API key like a password; do not embed it directly in client-side code or publicly expose it. The OpenAQ API Keys guide provides specific instructions on key generation and management.

The API key is typically passed in the X-API-Key header for each request. This is a common practice for API authentication, ensuring that only authorized applications can retrieve data. For more details on secure API key handling, refer to general best practices for API security, such as those outlined by Mozilla's documentation on HTTP authentication.

Your first request

After acquiring your API key, you can make your first request to the OpenAQ API. The API base URL is https://api.openaq.org/v2/. You will need to append an endpoint to this base URL and include your API key in the request header.

Example: Fetching Locations

One of the simplest endpoints to start with is /locations, which returns a list of available monitoring locations. The following examples demonstrate how to make this request using common programming languages.

Python Example

This Python script uses the requests library to fetch data from the /locations endpoint.


import requests
import os

# Replace with your actual API key or use an environment variable
API_KEY = os.getenv("OPENAQ_API_KEY", "YOUR_OPENAQ_API_KEY") 

headers = {
    "X-API-Key": API_KEY
}

base_url = "https://api.openaq.org/v2"
endpoint = "/locations"

response = requests.get(f"{base_url}{endpoint}", headers=headers)

if response.status_code == 200:
    data = response.json()
    # Print the first few locations to verify
    print("Successfully fetched data. First 3 locations:")
    for i, location in enumerate(data['results'][:3]):
        print(f"  Location Name: {location.get('name')}, Country: {location.get('country')}")
else:
    print(f"Error: {response.status_code} - {response.text}")

JavaScript (Node.js) Example

This Node.js example uses the built-in https module to make the GET request.


const https = require('https');

const API_KEY = process.env.OPENAQ_API_KEY || "YOUR_OPENAQ_API_KEY";

const options = {
  hostname: 'api.openaq.org',
  path: '/v2/locations',
  method: 'GET',
  headers: {
    'X-API-Key': API_KEY
  }
};

const req = https.request(options, (res) => {
  let data = '';
  console.log(`Status Code: ${res.statusCode}`);

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    if (res.statusCode === 200) {
      const result = JSON.parse(data);
      console.log('Successfully fetched data. First 3 locations:');
      result.results.slice(0, 3).forEach(location => {
        console.log(`  Location Name: ${location.name}, Country: ${location.country}`);
      });
    } else {
      console.error(`Error: ${res.statusCode} - ${data}`);
    }
  });
});

req.on('error', (e) => {
  console.error(`Request error: ${e.message}`);
});

req.end();

R Example

This R script utilizes the httr package for making HTTP requests and jsonlite for parsing JSON responses.


library(httr)
library(jsonlite)

# Replace with your actual API key or set as an environment variable
API_KEY <- Sys.getenv("OPENAQ_API_KEY", "YOUR_OPENAQ_API_KEY")

headers <- c(
  `X-API-Key` = API_KEY
)

base_url <- "https://api.openaq.org/v2"
endpoint <- "/locations"

response <- GET(paste0(base_url, endpoint), add_headers(.headers = headers))

if (http_status(response)$category == "Success") {
  data <- fromJSON(content(response, "text", encoding = "UTF-8"))
  cat("Successfully fetched data. First 3 locations:\n")
  for (i in 1:min(3, length(data$results))) {
    location <- data$results[[i]]
    cat(paste0("  Location Name: ", location$name, ", Country: ", location$country, "\n"))
  }
} else {
  cat(paste0("Error: ", http_status(response)$reason, " - ", content(response, "text")))
}

Common next steps

Once you have successfully made your first API call, you can explore the breadth of OpenAQ's data. Here are some common next steps:

  • Explore other endpoints: The OpenAQ API documentation details various endpoints beyond /locations, such as /measurements for specific air quality readings, /parameters for available measurement types, and /sources for data origin information.
  • Filter and query data: Learn how to use query parameters to filter results by geographic area, date range, parameter, or other criteria. This allows for more targeted data retrieval.
  • Handle pagination: For endpoints that return large datasets, understand how to navigate through paginated results to retrieve all relevant data.
  • Implement error handling: Integrate robust error handling into your application to gracefully manage API rate limits, invalid requests, or other potential issues.
  • Monitor API usage: Keep track of your API usage against your plan's limits, especially if you are on the Community Plan or a paid tier, to avoid unexpected service interruptions.
  • Integrate into an application: Begin incorporating the retrieved air quality data into dashboards, research tools, or other applications.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some typical problems and their solutions:

  • 401 Unauthorized: This usually indicates an issue with your API key.
    • Solution: Double-check that your API key is correct and included in the X-API-Key header of your request. Ensure there are no typos or leading/trailing spaces. Confirm your API key is active in your OpenAQ dashboard.
  • 403 Forbidden: This status code can mean your API key does not have the necessary permissions or your account has exceeded its rate limits.
    • Solution: Review your current OpenAQ plan and its associated rate limits. If you've recently signed up, ensure your account is fully activated.
  • 404 Not Found: This error suggests an incorrect endpoint path.
  • Network Issues: Problems with internet connectivity or firewall restrictions can prevent successful requests.
    • Solution: Check your internet connection. If working in a corporate environment, consult with your IT department regarding potential firewall or proxy issues that might block outbound HTTP requests.
  • Invalid JSON Response: If your code is failing to parse the response, the API might be returning an error message that is not valid JSON.
    • Solution: Always check the HTTP status code before attempting to parse the JSON body. If the status code indicates an error (e.g., 4xx or 5xx), the response body might contain a plain text error message or a different error format.