Authentication overview

IQAir's AirVisual API secures access to its comprehensive air quality data through a straightforward API key authentication mechanism. This method is common for web services requiring client identification without dealing with complex user-specific authorization flows. An API key is a unique identifier that authenticates the calling application or user to the API, associating requests with a specific IQAir account and its associated plan limits and permissions.

The IQAir AirVisual API provides access to real-time and forecast air quality data, including pollutant concentrations, dominant pollutant information, and weather conditions for over 10,000 locations worldwide. Proper authentication is essential for accessing this data, managing your API usage, and ensuring that your application complies with the terms of service. The API key must be included with every request to the API endpoints to validate the caller's identity and grant access to the requested resources, as detailed in the IQAir API reference documentation.

Supported authentication methods

IQAir exclusively utilizes API keys for authenticating requests to its AirVisual API. This method is suitable for a wide range of applications, particularly those where requests originate from server-side environments or controlled client-side applications that can securely manage the API key.

API keys offer a balance of simplicity and security when implemented correctly. They allow for easy integration and monitoring of API usage. While not providing the same granular authorization controls as OAuth 2.0, API keys are effective for services where the primary goal is to identify the calling application and enforce rate limits or access tiers. For more advanced authorization requirements typically associated with user data, developers might integrate additional identity management systems on their application's side.

The table below summarizes the authentication method supported by IQAir:

Method When to Use Security Level
API Key Server-side applications, public data access, controlled client-side access. Identifies developer/application. Moderate (requires secure storage and transmission over HTTPS).

Getting your credentials

To obtain your IQAir API key, you must first register for an IQAir AirVisual API account. The process typically involves these steps:

  1. Sign Up: Visit the IQAir AirVisual API pricing page and choose a plan. A free Developer Plan is available, offering 500 API calls per day for testing and small-scale projects.
  2. Account Creation: Complete the registration form, providing necessary contact and billing information if selecting a paid plan.
  3. Access Dashboard: Once registered and logged in, navigate to your personal dashboard or API key management section. The exact path may vary, but it's generally labeled 'API Keys' or 'Dashboard'.
  4. Generate Key: Your unique API key will be displayed or can be generated with a click. It is crucial to copy this key immediately and store it in a secure location, as it may not be retrievable again in plain text for security reasons.
  5. API Key Management: The dashboard also typically provides options to revoke existing keys or generate new ones, which is a critical security practice if a key is compromised or no longer needed. Always refer to the IQAir developer documentation for the most current and precise instructions on managing your API keys.

It is important to treat your API key as a sensitive credential. Never hardcode it directly into client-side code that could be publicly exposed, and restrict its usage to authorized environments.

Authenticated request example

Once you have obtained your API key, you will include it as a query parameter in all your API requests. The parameter name is typically key or token, as specified in the IQAir API reference.

Here's an example using cURL to retrieve current air quality data for a specific location. Replace YOUR_API_KEY with your actual IQAir API key and adjust the latitude and longitude as needed:

curl "https://api.iqair.com/v2/nearest_city?lat=34.0522&lon=-118.2437&key=YOUR_API_KEY"

This example demonstrates how the API key is appended to the URL as a query parameter. The API expects this parameter to authenticate the request. Similar patterns apply to other programming languages when constructing HTTP requests:

Python Example

import requests

api_key = "YOUR_API_KEY"
latitude = 34.0522
longitude = -118.2437
url = f"https://api.iqair.com/v2/nearest_city?lat={latitude}&lon={longitude}&key={api_key}"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print(f"Error: {response.status_code} - {response.text}")

JavaScript (Node.js with axios) Example

const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const latitude = 34.0522;
const longitude = -118.2437;
const url = `https://api.iqair.com/v2/nearest_city?lat=${latitude}&lon=${longitude}&key=${apiKey}`;

axios.get(url)
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(`Error: ${error.response ? error.response.status : error.message}`);
  });

These examples illustrate the general approach, but always consult the official IQAir AirVisual API documentation for specific endpoint details and parameter requirements.

Security best practices

Securing your API keys is paramount to protect your account from unauthorized access, prevent overuse, and maintain data integrity. Adhering to these best practices will help mitigate common security risks:

  • Keep API Keys Confidential: Never hardcode API keys directly into public client-side code (e.g., JavaScript in a web browser) or embed them in mobile applications without proper obfuscation and additional security layers. If a key is exposed, it can be used by anyone. Store keys in environment variables or secure configuration files on your server.
  • Use HTTPS/TLS: All communication with the IQAir API should occur over HTTPS to encrypt data in transit. This prevents eavesdropping and tampering with your API key and request data. The IQAir API inherently enforces HTTPS, but it's a fundamental security principle for any web service integration, as highlighted by Mozilla's explanation of TLS.
  • Restrict API Key Privileges: While IQAir API keys generally grant access to data retrieval, if future versions or related services offer more granular permissions, always apply the principle of least privilege. Grant only the necessary permissions for the key's intended function.
  • Rotate API Keys Regularly: Periodically generate new API keys and revoke old ones. This practice minimizes the window of opportunity for a compromised key to be exploited. A common rotation schedule might be every 90 days, or immediately if a compromise is suspected.
  • Monitor API Usage: Regularly check your IQAir API usage statistics in your dashboard. Unusual spikes in activity could indicate a compromised key or an unintended usage pattern in your application.
  • Implement Server-Side Access: For most applications, it is best to access the IQAir API from your own backend server rather than directly from a client application. Your server can securely store the API key and act as a proxy, making authenticated requests to IQAir and then serving the results to your frontend. This prevents exposure of the API key to end-users.
  • IP Whitelisting (if available): If IQAir offers IP whitelisting, configure your API key to only accept requests originating from a list of trusted IP addresses (e.g., your server's public IP). This adds an extra layer of security, preventing unauthorized use even if the key is stolen. Consult the IQAir developer documentation to see if this feature is supported for your plan.
  • Error Handling and Logging: Implement robust error handling for API responses, especially for authentication failures. Log these errors securely to monitor for potential attacks or misconfigurations without exposing sensitive information.

By following these guidelines, developers can significantly enhance the security posture of their applications integrating with the IQAir AirVisual API, safeguarding both their data and their account.