Most public APIs require an API key โ a unique string that identifies you as a registered user of the service.
Why API Keys Exist
Without a key, anyone could fire off unlimited requests and overload the server. A key lets the service:
- Know who is making requests
- Count them and enforce rate limits
- Revoke access if the key is abused
This isn’t a security mechanism against hacking โ a key is more like a badge: it says “I’m a registered user.”
What an API Key Looks Like
Usually a long random string:
a1b2c3d4e5f6789012345678abcdef01
Different services call it different things: API key, access token, app id, client secret. The concept is the same.
How to Pass a Key in a Request
Three common approaches:
1. Query parameter (like OpenWeatherMap):
https://api.openweathermap.org/data/2.5/weather?appid=YOUR_KEY
In code: params={"appid": API_KEY}.
2. Authorization header (like GitHub):
Authorization: Bearer YOUR_TOKEN
In code: headers={"Authorization": f"Bearer {TOKEN}"}.
3. X-API-Key header:
X-API-Key: YOUR_KEY
The API documentation for each service tells you which approach to use.
How NOT to Store Your Key
Never hardcode the key directly in your source file:
# DON'T โ if this ends up in git, the key becomes public
API_KEY = "a1b2c3d4e5f6789012345678abcdef01"
Bots constantly scan GitHub looking for exposed keys. If you accidentally publish one โ rotate it immediately.
The Right Way: a .env File
# .env โ this file is never committed to git
OPENWEATHER_API_KEY=a1b2c3d4e5f6789012345678abcdef01
from dotenv import load_dotenv
import os
load_dotenv()
API_KEY = os.getenv("OPENWEATHER_API_KEY")
The .env file lives only on your machine. Add it to .gitignore.
Limits and Free Tiers
Most APIs offer a free tier with a cap on the number of requests:
| Service | Free limit |
|---|---|
| OpenWeatherMap | 1,000 requests/day |
| NASA API | 1,000 requests/hour |
| GitHub API | 5,000 requests/hour |
When you exceed the limit, the server responds with 429 Too Many Requests.
Practical Notes
Keys Don’t Always Work Immediately
Some services (like OpenWeatherMap) activate a new key 10โ60 minutes after creation. During that window, requests return 401. This is normal โ just wait.
Lost or Compromised Key
Go to the service’s dashboard, generate a new key, and revoke the old one. Most services let you have multiple keys at the same time.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!