API Key Expired / Invalid Fix
In this tutorial, you'll learn about API Key Expired / Invalid Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Your API call returns 401 Unauthorized or API key invalid โ the API key expired, was revoked, is malformed, or lacks the required permissions.
Step-by-Step Fix
1. Check the API key format
# Wrong โ key with extra whitespace or quotes
curl -H "Authorization: Bearer 'sk-abc123def456'" https://api.example.com/v1/endpoint
# Right โ properly formatted header
curl -H "Authorization: Bearer sk-abc123def456" https://api.example.com/v1/endpoint
2. Verify the key is still active
# If the provider has a key validation endpoint
curl -X POST https://api.example.com/v1/keys/validate \
-H "Authorization: Bearer sk-abc123def456"
Expected output:
{
"valid": true,
"scopes": ["read", "write"],
"expires_at": "2025-06-24T00:00:00Z"
}
3. Fix expired key
import os
import requests
# Wrong โ using hardcoded expired key
API_KEY = "sk-old-expired-key-abc123"
# Right โ use environment variable and check expiry
API_KEY = os.environ.get("API_KEY")
if not API_KEY:
raise ValueError("API_KEY environment variable not set")
response = requests.get(
"https://api.example.com/v1/data",
headers={"Authorization": f"Bearer {API_KEY}"}
)
if response.status_code == 401:
# Check error message for "expired"
error_data = response.json()
if "expired" in error_data.get("error", ""):
print("API key expired. Generate a new key from the provider dashboard.")
# or use a refresh mechanism if available
4. Check key scopes
# Wrong โ key without required scopes
# Key has only "read" scope but we try to write
response = requests.post(
"https://api.example.com/v1/data",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"name": "test"}
)
# 403 Forbidden โ key lacks write scope
# Right โ ensure the key has the required scopes
# Generate a new key with "write" scope from the provider dashboard
API_KEY = os.environ.get("API_KEY_WRITE")
response = requests.post(
"https://api.example.com/v1/data",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"name": "test"}
)
# 201 Created
Common Mistakes
| Mistake | Fix |
|---|---|
| Hardcoded key expiry | Store keys in environment variables or a secrets manager |
| Key with wrong header format | Use Authorization: Bearer <key> for bearer tokens |
| Key copy-pasted with extra spaces | Trim whitespace: key.strip() |
| Using production key in dev environment | Use separate keys per environment with rate limit differences |
| Revoked key due to security policy | Check if the key was rotated by security policy and generate a new one |
Prevention
- Use environment variables or a secrets manager for API keys.
- Set up key rotation with a 30-day expiry cycle.
- Monitor API key usage and set alerts for 401 errors.
- Use API key management dashboards to revoke compromised keys.
DodaTech Tools
Doda Browser's credential manager stores API keys in an encrypted vault with expiry reminders. DodaZIP encrypts API key backups for disaster recovery. Durga Antivirus Pro monitors for exposed API keys in source code and configuration files.
Common Mistakes with key expired
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world API code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro