Authentication overview
AQICN's API utilizes a straightforward authentication model based on API keys. This approach ensures that only authorized applications and users can access the air quality data endpoints. An API key serves as a unique identifier and secret token that you include with each request to prove your identity and permissions. The API key model is commonly adopted by public APIs for its simplicity and ease of implementation, especially for read-only access to public data sets Google Cloud API Keys documentation. For AQICN, your API key is linked to your account and determines your access level, including your daily request quota, which starts with a free tier of 500 API calls per day and scales with paid plans.
Proper management of your API key is crucial to prevent unauthorized usage and potential service interruptions. Since the key acts as your credential, it should be protected like a password. Unauthorized access to your API key could lead to depletion of your daily quota, or in some cases, misuse of your account's privileges if broader permissions were ever assigned.
Supported authentication methods
The AQICN API exclusively supports API key authentication. This method is suitable for most direct server-to-server or client-to-server interactions where the key can be securely stored or transmitted. The API key is passed as a query parameter in the request URL.
API Key Authentication
This method involves appending your unique API key directly to the API endpoint URL as a query parameter. For example, a request might look like https://api.waqi.info/feed/<city>/?token=<YOUR_API_KEY>. This method is effective for identifying the calling application and applying rate limits or access controls.
Despite its simplicity, developers should be aware of the security implications of transmitting keys in URLs. While HTTPS encrypts the entire request, including query parameters, API keys in URLs can sometimes be logged in server logs, browser histories, or proxy servers, making them vulnerable if not handled with care. For sensitive operations or APIs handling private user data, more robust methods like OAuth 2.0 or JWTs (JSON Web Tokens) are generally preferred MDN Web Docs on HTTP Authentication. However, for AQICN's public air quality data, the API key approach provides a practical balance of security and ease of use.
Here's a table summarizing the supported authentication method:
| Method | When to Use | Security Level |
|---|---|---|
| API Key (Query Parameter) | Accessing public air quality data; applications where the key can be securely stored (e.g., backend servers); scripts and non-commercial projects. | Moderate (requires HTTPS for transport security; key exposure risk via logs/history if not carefully managed). |
Getting your credentials
To obtain your AQICN API key, you need to register for an account on the AQICN website. The process is straightforward and typically involves a few steps:
- Visit the AQICN API Website: Navigate to the AQICN API documentation page.
- Sign Up/Log In: If you don't have an account, you will need to sign up. This usually involves providing an email address and creating a password. If you already have an account, simply log in.
- Access Your Dashboard: After logging in, you should be redirected to your user dashboard or a similar account management area.
- Locate API Key Section: Within your dashboard, there will be a section dedicated to API keys. This is where your unique key will be displayed. You might need to generate a new key if it's your first time or if you need to revoke and replace an existing one.
- Copy Your API Key: Carefully copy your API key. It is a long alphanumeric string.
Once you have your API key, you can start making requests to the AQICN API. Remember that the API usage is subject to your plan's limits, starting with the free tier. Your dashboard will also typically provide information on your current usage and remaining quota.
Authenticated request example
The following examples demonstrate how to make an authenticated request to the AQICN API using common programming languages. Replace YOUR_API_KEY with your actual key and city with the desired location (e.g., shanghai or london).
Python Example
import requests
api_key = "YOUR_API_KEY"
city = "beijing"
url = f"https://api.waqi.info/feed/{city}/?token={api_key}"
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
JavaScript (Node.js with fetch) Example
const fetch = require('node-fetch');
const apiKey = "YOUR_API_KEY";
const city = "new-york";
const url = `https://api.waqi.info/feed/${city}/?token=${apiKey}`;
async function getAirQuality() {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching air quality data:', error);
}
}
getAirQuality();
cURL Example
curl "https://api.waqi.info/feed/tokyo/?token=YOUR_API_KEY"
In all examples, the API key is passed directly in the URL as the token query parameter. Successful responses will return JSON data containing air quality information for the specified city. Error responses will typically include status codes and messages indicating the nature of the issue, such as an invalid or missing API key, or rate limit exceeded.
Security best practices
While API key authentication is straightforward, adhering to security best practices is essential to protect your credentials and maintain the integrity of your application and AQICN account. Implementing these practices helps mitigate common vulnerabilities associated with API key usage.
-
Use HTTPS Everywhere: Always ensure that all your API requests are made over HTTPS. This encrypts the communication channel between your application and the AQICN server, preventing attackers from intercepting your API key in transit. AQICN's API endpoints are served over HTTPS by default, but it's crucial to confirm your client library or code explicitly uses
https://in the URL. - Do Not Embed Keys in Client-Side Code: Never hardcode or embed your API key directly into client-side code (e.g., JavaScript in a web browser, mobile application front-end). If your application requires client-side access, consider using a backend proxy server that makes the API calls on behalf of the client, protecting your API key from exposure.
- Store Keys Securely: Store your API keys in environment variables, configuration files, or secure secret management services rather than directly in your source code repository. For server-side applications, use environment variables. For cloud deployments, leverage services like AWS Secrets Manager AWS Secrets Manager introduction or Google Cloud Secret Manager Google Cloud API Keys documentation. Version control systems like Git should always ignore files containing API keys.
- Restrict API Key Privileges (if applicable): Although AQICN API keys primarily grant access to air quality data, if AQICN were to introduce more granular permissions in the future, always configure your API keys with the minimum necessary privileges. This principle of least privilege limits the potential damage if a key is compromised.
- Monitor API Usage: Regularly monitor your API usage through your AQICN dashboard. Unusual spikes in usage could indicate that your API key has been compromised or that your application has a bug leading to excessive requests. Promptly investigate any anomalies.
- Implement Rate Limit Handling: Understand and gracefully handle AQICN's rate limits. Incorrect handling of rate limits can lead to your key being temporarily blocked. Implement exponential backoff and retry mechanisms in your application to manage these situations effectively.
- Rotate API Keys: Periodically rotate your API keys. This practice minimizes the window of opportunity for a compromised key to be exploited. If you suspect a key has been compromised, immediately revoke it via your AQICN dashboard and generate a new one.
- Secure Development Environment: Ensure that your development environment is secure. This includes using strong passwords, keeping software updated, and being cautious about sharing development keys. Treat all keys used in development with the same care as production keys.
By following these best practices, developers can significantly enhance the security posture of their applications integrating with the AQICN API, ensuring both data integrity and service reliability.