SDKs overview

Purple Air provides a public API that allows developers to access real-time and historical air quality data from its global network of sensors. To facilitate interaction with this API, developers can utilize a range of Software Development Kits (SDKs) and community-contributed libraries. These tools abstract the underlying HTTP requests and data parsing, enabling more efficient integration of air quality data into custom applications, dashboards, or research projects. The official documentation offers comprehensive guides for API key acquisition and usage protocols to ensure secure and efficient data retrieval, as detailed in the Purple Air API Reference.

Using an SDK or library simplifies common tasks such as authenticating requests, constructing API queries, and handling responses. This approach can accelerate development cycles by providing pre-built functions and methods tailored to the Purple Air API's structure. While an official SDK for every major programming language may not be available directly from Purple Air, the developer community often contributes libraries that extend support to a wider array of environments, reflecting the open nature of many API ecosystems, as described by Mozilla's API key documentation.

Official SDKs by language

Purple Air's primary focus for official SDKs and direct API support centers around widely used languages for data processing and web development. The following table outlines the key official resources available, including their respective packages and installation methods. These official offerings are maintained by Purple Air to ensure compatibility with the latest API versions and data models.

Language Package/Library Name Installation Command Maturity
Python purpleair-api-client pip install purpleair-api-client Stable
JavaScript (Node.js/Browser) purpleair-api-js npm install purpleair-api-js Stable

Installation

Installing Purple Air SDKs typically follows standard package management practices for the respective programming languages. Ensure you have the necessary runtime environment and package manager installed before proceeding. For Python, pip is the standard package installer, while for JavaScript environments, npm (Node Package Manager) is commonly used. Detailed instructions are available within the official Purple Air documentation portal.

Python

To install the official Python client for the Purple Air API, use pip:

pip install purpleair-api-client

This command downloads and installs the package and its dependencies, making the client available for import in your Python projects. It is recommended to use a virtual environment to manage project dependencies, as suggested by general Python best practices documented by Microsoft's Python environment setup guide.

JavaScript

For JavaScript projects, whether in a Node.js backend or a browser-based frontend, install the client using npm:

npm install purpleair-api-js

This command adds the purpleair-api-js package to your project's node_modules directory and updates your package.json file. You can then import the library into your JavaScript files using standard ES modules or CommonJS syntax.

Quickstart example

The following examples demonstrate how to use the official Python and JavaScript SDKs to fetch sensor data from the Purple Air API. Before running these examples, ensure you have obtained an API key from your Purple Air account dashboard and replaced the placeholder YOUR_API_KEY.

Python Quickstart

This Python example fetches data for a specific sensor ID. The purpleair-api-client simplifies authentication and data retrieval, returning parsed JSON responses.

import os
from purpleair_api import PurpleAirAPI

# Replace with your actual API key
API_KEY = os.environ.get("PURPLEAIR_API_KEY", "YOUR_API_KEY")

# Replace with a valid sensor ID, e.g., from the Purple Air map
SENSOR_ID = 12345

def get_sensor_data():
    try:
        pa = PurpleAirAPI(API_KEY)
        # Fetch data for a single sensor
        sensor_data = pa.get_single_sensor_data(SENSOR_ID, read_key=None, fields="pm2.5_10minute,humidity,temperature")
        
        if sensor_data:
            print(f"Sensor ID: {SENSOR_ID}")
            print(f"PM2.5 (10-minute avg): {sensor_data['pm2.5_10minute']} µg/m³")
            print(f"Humidity: {sensor_data['humidity']}%")
            print(f"Temperature: {sensor_data['temperature']}°F")
        else:
            print(f"No data found for sensor ID {SENSOR_ID}")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    get_sensor_data()

JavaScript Quickstart (Node.js)

This Node.js example uses the purpleair-api-js library to perform a similar operation, fetching data for a specified sensor.

const PurpleAirAPI = require('purpleair-api-js');

// Replace with your actual API key
const API_KEY = process.env.PURPLEAIR_API_KEY || 'YOUR_API_KEY';

// Replace with a valid sensor ID, e.g., from the Purple Air map
const SENSOR_ID = 12345;

async function getSensorData() {
    try {
        const pa = new PurpleAirAPI(API_KEY);
        const sensorData = await pa.getSensorData(SENSOR_ID, { fields: 'pm2.5_10minute,humidity,temperature' });

        if (sensorData && sensorData.sensor) {
            console.log(`Sensor ID: ${SENSOR_ID}`);
            console.log(`PM2.5 (10-minute avg): ${sensorData.sensor['pm2.5_10minute']} µg/m³`);
            console.log(`Humidity: ${sensorData.sensor.humidity}%`);
            console.log(`Temperature: ${sensorData.sensor.temperature}°F`);
        } else {
            console.log(`No data found for sensor ID ${SENSOR_ID}`);
        }
    } catch (error) {
        console.error(`An error occurred: ${error.message}`);
    }
}

getSensorData();

These examples illustrate how to initialize the API client with your key and then call methods to retrieve specific sensor information. The fields parameter is crucial for requesting only the necessary data points, optimizing bandwidth and processing, as outlined in the Purple Air Get Sensor Data endpoint documentation.

Community libraries

Beyond the officially supported SDKs, the developer community has created various libraries and tools to interact with the Purple Air API. These community-driven projects can offer support for additional programming languages, frameworks, or specialized use cases not covered by official offerings. While not officially maintained by Purple Air, these libraries often provide valuable resources for specific development needs.

  • R Packages: Several R packages exist for environmental data analysis that can integrate with Purple Air data. These often focus on statistical analysis and visualization, leveraging R's strengths in data science.
  • Go/Rust Clients: Developers in Go and Rust communities have sometimes created client libraries for highly performant applications or microservices, demonstrating the language's suitability for system-level integrations, as discussed in various Go language frequently asked questions.
  • Dashboard Integrations: Community efforts also extend to pre-built integrations with popular data visualization dashboards (e.g., Grafana, Home Assistant), allowing users to display Purple Air data alongside other environmental metrics.

When considering community libraries, it is important to evaluate their maintenance status, documentation, and active community support. Developers should refer to the Purple Air API documentation for the authoritative source on API endpoints and data structures, regardless of the client library being used, to ensure compatibility and correct data interpretation.