API Security Patterns
APIs are prime targets for attackers. They're publicly accessible, handle sensitive data, and often connect directly to databases. Securing APIs requires multiple layers of protection — authentication to verify identity, authorization to control access, rate limiting to prevent abuse, and input validation to block malicious data.
Authentication Methods
Different scenarios call for different authentication approaches:
API Keys: Simple tokens that identify the client. Good for server-to-server communication where you trust the client to keep the key secret.
Authorization: Api-Key sk_live_abc123xyz
JWT Tokens: Self-contained tokens that include user information and expiration. Stateless and scalable, but require careful handling of token refresh.
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
OAuth 2.0: Delegated authorization for third-party access. Users grant limited permissions without sharing credentials. Essential for integrations.
Rate Limiting
Rate limiting prevents abuse and ensures fair resource usage. Communicate limits clearly through headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1623456789
When limits are exceeded, return 429 Too Many Requests with information about when to retry:
{
"error": {
"code": "RATE_LIMITED",
"message": "Too many requests",
"retryAfter": 60
}
}
Consider different limits for different endpoints — read operations can often be more generous than writes.
Input Validation
Never trust client input. Validate everything:
- Type checking: Ensure fields are the expected type
- Length limits: Prevent oversized payloads
- Format validation: Verify emails, URLs, dates are properly formatted
- Allowed values: Reject unexpected enum values
- Sanitization: Clean input before use, especially for SQL or HTML contexts
# Reject unexpected fields
allowed_fields = {'email', 'name', 'role'}
if set(request.json.keys()) - allowed_fields:
return error_response("Unexpected fields in request")
Security Headers
Set appropriate headers on responses:
Content-Type: application/json
X-Content-Type-Options: nosniff
The nosniff header prevents browsers from interpreting responses as something other than the declared content type — a defense against certain attacks.
HTTPS Only
APIs should only be accessible over HTTPS. Reject HTTP requests or redirect them. Sensitive data should never travel unencrypted.
See More
- What Is Application Security?
- Authentication and Authorization
- Input Validation and Sanitization
- Rate Limiting