Getting started overview
Getting started with the Purple Air API involves a sequence of steps to provision access and retrieve air quality data. The primary objective is to obtain an API key, which authenticates requests to the Purple Air platform. This key grants programmatic access to the global network of Purple Air sensors, enabling retrieval of real-time and historical air quality readings. The process typically begins with creating a Purple Air user account, followed by registering for API access within the developer portal. Once the API key is secured, developers can construct HTTP requests to specific API endpoints, such as those for retrieving sensor data or sensor metadata. The Purple Air API primarily utilizes RESTful principles, accepting requests via standard HTTP methods and returning data in JSON format PurpleAir API Reference documentation. Understanding basic HTTP request structures and JSON parsing is beneficial for efficient integration.
The Purple Air API supports various filtering and query parameters to refine data requests, allowing developers to specify sensor IDs, data fields, or time ranges. This granular control over data retrieval is essential for applications requiring specific air quality information. Security best practices, such as keeping API keys confidential and avoiding hardcoding them directly into client-side applications, are important for maintaining the integrity of data access Google Maps API security best practices. The platform provides comprehensive documentation to guide developers through the API's capabilities and usage patterns, ensuring that the integration process is clear and supported.
Quick reference table
| Step | What to do | Where |
|---|---|---|
| 1. Create Account | Register for a Purple Air user account. | PurpleAir Registration Page |
| 2. Get API Key | Apply for and retrieve your API key from the developer portal. | PurpleAir API Key Section |
| 3. Understand Endpoints | Review available API endpoints and data structures. | PurpleAir API Reference |
| 4. Make Request | Construct an HTTP GET request with your API key. | PurpleAir Making a Request Guide |
| 5. Process Response | Parse the JSON response to extract air quality data. | MDN JSON.parse() documentation |
Create an account and get keys
To begin using the Purple Air API, the initial step involves creating a user account on the Purple Air website. This account serves as the foundation for accessing both the public sensor map and the developer portal PurpleAir Homepage. Navigate to the registration page and provide the necessary information, such as an email address and a password, to establish your account. Once registered, verify your email address if prompted, as this is a common security measure for new accounts.
After successfully creating and logging into your Purple Air account, the next critical step is to obtain an API key. The API key is a unique identifier that authenticates your application when it makes requests to the Purple Air API. Without a valid API key, most API endpoints will return an authentication error. To acquire an API key, proceed to the Purple Air developer documentation or API section, which is typically accessible through your account dashboard or a dedicated developer portal link PurpleAir API Key acquisition instructions. The process usually involves agreeing to the API terms of service and then generating a new key. Purple Air provides two types of API keys: a 'Read' key for retrieving data and a 'Write' key for sending data (e.g., if you are contributing sensor data). For typical data consumption, a 'Read' key is sufficient.
Once generated, your API key will be displayed. It is crucial to store this key securely, as it grants access to Purple Air's data resources. Avoid embedding the key directly into public client-side code or sharing it unnecessarily. Best practices suggest using environment variables or a secure configuration management system to manage API keys in server-side applications. If your API key is compromised, you should regenerate it immediately through the Purple Air developer portal to invalidate the old key and prevent unauthorized access.
Your first request
With an API key in hand, you can now make your first request to the Purple Air API. The primary goal for a first request is often to retrieve data from a specific sensor or a list of nearby sensors. The Purple Air API is RESTful, meaning you will use standard HTTP methods, primarily GET, to fetch data from designated URLs (endpoints). All API requests must include your API key in the request headers.
Retrieving sensor data
A common starting point is to fetch data from a known sensor. You will need the sensor_index of the sensor you wish to query. You can find sensor indices by browsing the PurpleAir Map and clicking on a sensor, which reveals its details including the index, or by using the /sensors endpoint which lists available sensors PurpleAir /sensors endpoint documentation.
Here's an example using curl to retrieve data for a specific sensor (replace YOUR_API_KEY and YOUR_SENSOR_INDEX with your actual values):
curl -X GET \
'https://api.purpleair.com/v1/sensors/YOUR_SENSOR_INDEX' \
-H 'X-API-Key: YOUR_API_KEY' \
-H 'Content-Type: application/json'
This request targets the /v1/sensors/{sensor_index} endpoint. The -H 'X-API-Key: YOUR_API_KEY' part adds your API key to the request header, which is how the API authenticates your call. The -H 'Content-Type: application/json' header indicates that you expect a JSON response.
Upon a successful request, the API will return a JSON object containing various data points for the specified sensor, such as particulate matter concentrations (PM2.5, PM10), temperature, humidity, and pressure. The structure of the JSON response is detailed in the PurpleAir sensor data endpoint reference.
Example response structure (truncated for brevity)
{
"api_version": "V1.0.11-0.0.31",
"time_stamp": 1678886400,
"data": {
"sensor_index": 123456,
"name": "My PurpleAir Sensor",
"latitude": 34.0522,
"longitude": -118.2437,
"pm2_5_atm": 8.5,
"humidity": 65.2,
"temperature": 22.1,
"pressure": 1012.5,
"last_seen": 1678886390
// ... more data fields
}
}
Parsing this JSON response in your chosen programming language will allow you to extract the specific air quality metrics needed for your application. For example, in Python, you might use the json library to load the response and access fields like data['pm2_5_atm'].
Common next steps
After successfully making your first request and retrieving sensor data, several common next steps can enhance your integration with the Purple Air API:
- Explore Additional Endpoints: The Purple Air API offers various endpoints beyond single sensor data. Investigate endpoints for retrieving multiple sensors within a geographic area (
/sensorswith location parameters), historical data (if available for your access level), or sensor metadata PurpleAir API Reference documentation. - Implement Error Handling: Robust applications anticipate and gracefully handle API errors. Familiarize yourself with common HTTP status codes (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error) and how the Purple Air API communicates error messages in its responses PurpleAir API error handling guide.
- Data Processing and Visualization: Raw air quality data often requires processing. Consider applying correction factors (like the LRAPA or EPA conversion for PM2.5) if recommended for your use case PurpleAir data conversion formulas. Then, visualize the data using charting libraries or mapping tools to make it interpretable.
- Rate Limiting Management: Be aware of any rate limits imposed by the Purple Air API to prevent your application from being blocked. Implement strategies like exponential backoff for retries and cache data where possible to reduce the number of requests PurpleAir API rate limit guidelines.
- Secure API Key Management: Revisit how your API key is stored and used. For production applications, avoid hardcoding the key. Instead, use environment variables, cloud secrets managers, or secure configuration files.
- Webhooks and Real-time Updates: If your application requires real-time updates without constant polling, investigate if Purple Air offers webhook capabilities or other push mechanisms. While not explicitly detailed as a primary API feature for general users, some platforms offer this for specific use cases.
- Explore SDKs and Libraries: While
curlis useful for initial testing, consider using a client library or SDK in your preferred programming language if one is available. These often abstract away HTTP request complexities and provide language-specific interfaces for easier integration.
Troubleshooting the first call
When making your first API call to Purple Air, encountering issues is common. Here are some troubleshooting steps:
1. Check API Key
- Incorrect Key: Ensure your API key is copied correctly and includes no leading or trailing spaces.
- Header Format: Verify that the API key is passed in the
X-API-KeyHTTP header, as specified in the PurpleAir authentication documentation. - Key Type: Confirm you are using a 'Read' key for data retrieval. 'Write' keys are for pushing data to sensors.
- Key Expiration/Revocation: Check if your API key has expired or been revoked in your Purple Air account settings.
2. Verify Endpoint and Parameters
- Incorrect URL: Double-check the API endpoint URL for typos. The base URL is
https://api.purpleair.com/v1/. - Missing Sensor Index: If querying a specific sensor, ensure the
sensor_indexis correctly included in the URL path. - Required Parameters: Review the PurpleAir API Reference for the specific endpoint you are calling to ensure all required parameters are present and correctly formatted.
- HTTP Method: Confirm you are using the correct HTTP method (e.g.,
GETfor data retrieval).
3. Inspect Response and Status Codes
- 401 Unauthorized: This almost always indicates an issue with your API key (missing, incorrect, or invalid). Re-verify your key and its placement in the
X-API-Keyheader. - 404 Not Found: The requested resource (e.g., a sensor with that
sensor_index) does not exist or the URL path is incorrect. Verify thesensor_indexand the endpoint path. - 400 Bad Request: This usually means there's an issue with your request parameters (e.g., incorrect format for a query parameter). The API response body often contains a more specific error message.
- 5xx Server Errors: These indicate an issue on Purple Air's side. While less common for a first call, if you encounter these, it's best to check the PurpleAir status page or try again later.
- Empty or Unexpected JSON: If the request succeeds but the JSON is empty or not what you expect, check if your query parameters are too restrictive or if the sensor you're querying has no data.
4. Check Network Connectivity and Tools
- Internet Connection: Ensure your device has an active internet connection.
- Firewall/Proxy: If you are in a corporate network, a firewall or proxy might be blocking outbound requests. Consult your network administrator.
curlSyntax: If usingcurl, ensure the syntax is correct, especially for quotes and backslashes. Different shells (Bash, PowerShell, CMD) can interpret these differently.- Programming Language Libraries: If using a library (e.g., Python's
requests), ensure it's installed correctly and you're handling the response object as per its documentation.
By systematically checking these points, you can identify and resolve most issues encountered during your initial Purple Air API integration.