# Extract WAQI Air Quality Data with Forecasts (`muhammadafzal/waqi-air-quality-scraper`) Actor

Extract real-time WAQI AQI, pollutant readings, weather, station coordinates, attribution, and forecasts for cities, stations, searches, and map bounds.

- **URL**: https://apify.com/muhammadafzal/waqi-air-quality-scraper.md
- **Developed by:** [Muhammad Afzal](https://apify.com/muhammadafzal) (community)
- **Categories:** Automation, Developer tools, MCP servers
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 1,000 air-quality record returneds

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## WAQI Air Quality Scraper

Extract current air-quality observations from the World Air Quality Index (WAQI) for cities, monitoring stations, coordinates, station searches, and map bounding boxes. The actor returns clean, agent-friendly JSON with AQI, the dominant pollutant, PM2.5, PM10, ozone, NO2, SO2, CO, weather readings, station coordinates, observation timestamps, attribution links, and optional daily forecasts.

### What this actor returns

Each dataset row represents one unique WAQI feed. The main fields are:

- `station_uid`, `station_name`, `city_name`, `city_url`
- `latitude`, `longitude`, `observation_time`
- `aqi`, `aqi_category`, `dominant_pollutant`
- `pm25`, `pm10`, `o3`, `no2`, `so2`, and `co`
- `temperature_c`, `humidity_pct`, `pressure_hpa`, and `wind_speed_mps`
- `forecast_daily` when WAQI supplies a forecast
- `attribution_names`, `attribution_urls`, `source_url`, `scraped_at`, and `warnings`

Missing measurements are returned as `null`, while optional arrays are returned as `[]`. Every record has the same shape so it can be consumed reliably by AI agents, CSV exports, dashboards, and scheduled workflows.

### Input modes

#### Cities or stations

Use `locations` for exact city or station feeds:

```json
{
  "locations": ["Shanghai", "London", "@12345"],
  "maxResults": 10,
  "includeForecast": true
}
```

You may use a station ID such as `@12345`, a city name, or a WAQI `geo:latitude;longitude` value. The actor accepts the aliases `location`, `city`, and `station` when called programmatically by an AI agent.

#### Coordinates

Use `coordinates` to ask WAQI for the nearest feed to one or more points:

```json
{
  "coordinates": [
    { "latitude": 31.2304, "longitude": 121.4737 },
    { "latitude": 51.5074, "longitude": -0.1278 }
  ]
}
```

#### Station search

Use `searchQueries` when you want WAQI to find stations by city, country, station name, or native-language text. The actor performs the search and then fetches the full feed for each matching station.

```json
{ "searchQueries": ["Bangalore", "Bulgaria"], "maxResults": 25 }
```

#### Map bounds

Use `bounds` for station inventories inside a rectangle. Values are `south,west,north,east`:

```json
{ "bounds": ["22.01,112.69,22.37,113.02"], "maxResults": 50 }
```

The actor also accepts a WAQI API URL or a public `aqicn.org/city/{slug}` URL through `startUrls`.

### WAQI token and responsible use

Set `WAQI_TOKEN` as an Apify actor environment variable. Without a token, city inputs use the public AQICN city-page fallback; coordinates, searches, bounds, forecasts, and richer station fields require your own token. Register at [aqicn.org/data-platform/register](https://aqicn.org/data-platform/register) before scheduled or production runs. Do not put a private token in normal input; environment variables keep it out of input history and ordinary logs.

WAQI requires attribution to the World Air Quality Index project and the originating EPA or agency. The actor keeps attribution names and URLs in every row and includes the source URL for traceability. Review the current [WAQI API terms](https://aqicn.org/api/) before using the results. Those terms restrict redistribution, cached or archived data, paid applications, and public for-profit use unless the required agreement or permission is in place. This actor is therefore intended for authorized, compliant use; Apify PPE does not override WAQI’s terms.

### Pricing

The actor defines two billable events: a small actor-start event and `air-quality-record` at `$0.005` per unique dataset row. Your final Apify bill may also include the platform’s normal compute and proxy usage charges. The maximum result-event cost is `maxResults × $0.005`; for example, 25 records has a result-event cap of `$0.125`.

### API and automation

The actor can be run from the Apify Console, API, CLI, schedules, or MCP-compatible agents. A typical API input is:

```bash
curl "https://api.apify.com/v2/acts/YOUR_USERNAME~waqi-air-quality-scraper/runs?token=YOUR_APIFY_TOKEN" \
  -X POST \
  -H 'Content-Type: application/json' \
  -d '{"locations":["London"],"maxResults":1}'
```

Use the dataset output for current readings, and the `OUTPUT` key-value record for the run summary. The actor stops at `maxResults`, deduplicates repeated stations, retries transient HTTP failures, and reports non-fatal API warnings without adding error objects to the dataset.

JavaScript callers can use the Apify API with the same input:

```js
const response = await fetch(
  `https://api.apify.com/v2/acts/${process.env.APIFY_USERNAME}~waqi-air-quality-scraper/runs?token=${process.env.APIFY_TOKEN}`,
  {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ locations: ['London'], maxResults: 1 }),
  },
);
console.log(await response.json());
```

### FAQ

#### Does this actor need a browser or login?

No. The primary path uses the official WAQI JSON API through a lightweight HTTP crawler. A public AQICN city-page fallback is available for city inputs when no token is configured. The actor does not bypass login walls, captchas, or access controls.

#### What is the difference between `locations` and `searchQueries`?

Use `locations` for an exact city, station name, station ID, or geo feed. Use `searchQueries` when you want WAQI to discover matching stations by keyword, country, or native-language name. Search, coordinate, and map-bounds modes require `WAQI_TOKEN`.

#### Are pollutant values concentrations?

WAQI’s `iaqi` fields and the public fallback values are pollutant-specific AQI values. They are not guaranteed raw mass concentrations in a particular unit. Use the attribution and source URL fields when interpreting or displaying them.

#### Can I resell the data?

Review WAQI’s current terms before any redistribution, caching, paid application, or public commercial use. The actor’s Apify pricing does not grant rights beyond the source’s terms.

### Local development

```bash
npm install
npm test
apify run
```

For production, set `WAQI_TOKEN` in the actor environment and use a current Apify build. The default empty input intentionally runs a small Shanghai city-page health check so Apify’s automated health test has a valid sample without additional configuration.

# Actor input Schema

## `locations` (type: `array`):

Use this for one or more WAQI city names, station names, station IDs such as @12345, or geo strings such as geo:31.23;121.47. Use coordinates for latitude/longitude and searchQueries when you want WAQI station search. Defaults to Shanghai.

## `searchQueries` (type: `array`):

Use this when you want WAQI to find matching stations by name, city, country, or native-language text. The actor then fetches full AQI and pollutant data for matching stations. Do not use this for an exact station ID; use locations instead.

## `coordinates` (type: `array`):

Use this for one or more geographic points. Each item must contain latitude and longitude, for example \[{"latitude": 31.2304, "longitude": 121.4737}]. The actor uses WAQI's nearest-station geo feed.

## `bounds` (type: `array`):

Use this to list stations inside bounding boxes formatted as south,west,north,east, for example 22.01,112.69,22.37,113.02. This is useful for map or regional station inventories; use locations for a single city feed.

## `startUrls` (type: `array`):

Use this when you already have a WAQI API feed URL or a public AQICN city URL. API URLs are used directly; public /city/{slug} pages are converted to the official WAQI feed endpoint. This supplements locations and searchQueries.

## `maxResults` (type: `integer`):

Use this to cap total unique station or city records returned across all inputs. Enter 1 to 1000; defaults to 10. This is a result cap, not a per-query cap.

## `includeForecast` (type: `boolean`):

Use this when you need WAQI daily pollutant forecasts in addition to current AQI and readings. Defaults to true. Set false for a smaller current-conditions-only dataset.

## `requestDelayMs` (type: `integer`):

Use this to add respectful pacing between WAQI API calls. Defaults to 250 milliseconds; use 0 only for small authorized test runs.

## Actor input object example

```json
{
  "locations": [
    "Shanghai"
  ],
  "searchQueries": [],
  "coordinates": [],
  "bounds": [],
  "startUrls": [],
  "maxResults": 10,
  "includeForecast": true,
  "requestDelayMs": 250
}
```

# Actor output Schema

## `results` (type: `string`):

Link to the dataset containing structured WAQI current conditions, pollutant readings, forecast values, station coordinates, timestamps, and required attribution fields.

## `summary` (type: `string`):

Run summary is stored in the OUTPUT key-value record with recordsCollected, chargedEvents, spentUsd, and warnings.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "locations": [
        "Shanghai"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("muhammadafzal/waqi-air-quality-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "locations": ["Shanghai"] }

# Run the Actor and wait for it to finish
run = client.actor("muhammadafzal/waqi-air-quality-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "locations": [
    "Shanghai"
  ]
}' |
apify call muhammadafzal/waqi-air-quality-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,muhammadafzal/waqi-air-quality-scraper"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/18oqFfxJIUZbAUJSw/builds/A7y4Ye5Yh4RX3bOv2/openapi.json
