(AQI)Air Quality Data

With the increasing air pollution caused by temperature inversions in recent days, I created a resource to make air quality data more accessible. This interactive map allows users to explore and download Realtime AQI data.
🔹 The map is built using the API from Iran’s National Air Quality Monitoring System.
🔹 You can easily download the data and use it for your analyses.
🔹 Tools like Python can be used to work with this Api as well.

				
					import requests
import sqlite3
from datetime import datetime, timedelta

# Configuration
API_TOKEN = "***"
DATABASE_FILE = "iran_aqi_data.db"
IRAN_BOUNDS = "39.782135,44.038547,25.064043,63.317140"  # North, West, South, East coordinates

# Database Setup
def init_db():
    conn = sqlite3.connect(DATABASE_FILE)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS aqi_data (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            station_id TEXT,
            station_name TEXT,
            latitude REAL,
            longitude REAL,
            aqi INTEGER,
            timestamp TEXT
        )
    ''')
    conn.commit()
    return conn

# Fetch AQI Data
def fetch_aqi(bounds):
    url = f"https://api.waqi.info/v2/map/bounds/?latlng={bounds}&token={API_TOKEN}"
    response = requests.get(url)
    data = response.json()
    if data['status'] != 'ok':
        raise Exception(f"API Error: {data.get('data', 'Unknown error')}")
    return data['data']

# Save Data to Database
def save_to_db(conn, stations):
    cursor = conn.cursor()
    for station in stations:
        cursor.execute('''
            INSERT INTO aqi_data (station_id, station_name, latitude, longitude, aqi, timestamp)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (
            station['uid'],
            station['station']['name'],
            station['lat'],
            station['lon'],
            station['aqi'],
            datetime.utcnow().isoformat()
        ))
    conn.commit()

# Main Script
def main():
    conn = init_db()
    try:
        stations = fetch_aqi(IRAN_BOUNDS)
        save_to_db(conn, stations)
        print("Data saved successfully.")
    except Exception as e:
        print(f"Error: {e}")
    finally:
        conn.close()

if __name__ == "__main__":
    main()