API Keys — Complete Service Authentication Guide
In this tutorial, you will learn about API Keys. We cover key concepts, practical examples, and best practices to help you master this topic.
API keys are unique identifiers issued to clients for authentication. They are simpler than OAuth 2.0 or JWT and are commonly used for service-to-service communication and developer API access.
What You'll Learn
You'll learn API key generation, validation, security best practices, and when to use them vs other auth methods.
Why It Matters
API keys power massive ecosystems including Stripe, Twilio, Google Maps, and OpenAI. Understanding their security trade-offs is essential for any API developer.
Real-World Use
A weather API issues API keys to developers. Each key has a usage tier (free: 1000/day, pro: 100000/day) and can be revoked if terms are violated. Keys are hashed in the database.
sequenceDiagram
participant Dev as Developer
participant API as API Service
Dev->>API: Register Account
API->>Dev: API Key (sk_live_xxx)
Dev->>API: Request (X-API-Key: sk_live_xxx)
API->>API: Hash key, look up permissions
API->>Dev: Response
Implementation
import hashlib
import secrets
from flask import Flask, request, jsonify
app = Flask(__name__)
API_KEYS_DB = {}
def generate_api_key():
raw = f"doda_{secrets.token_urlsafe(32)}"
hashed = hashlib.sha256(raw.encode()).hexdigest()
return raw, hashed
def validate_api_key(request):
api_key = request.headers.get("X-API-Key")
if not api_key:
return None
hashed = hashlib.sha256(api_key.encode()).hexdigest()
return API_KEYS_DB.get(hashed)
raw_key, hashed = generate_api_key()
API_KEYS_DB[hashed] = {"client": "Acme Corp", "tier": "pro"}
print(f"Key: {raw_key}")
Common Mistakes
| Mistake | Fix |
|---|---|
| Keys in URL or query params | Always use header (X-API-Key) |
| Plain text storage | Hash with SHA-256 before storing |
| No key rotation | Support key regeneration |
| One key for everything | Support scoped keys |
| No usage tracking | Log every API key usage |
What's Next
Learn about HTTP Basic Authentication.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro