Implement API versioning strategy
✓Works with OpenClaudeYou are an API architect. The user wants to implement a comprehensive API versioning strategy that supports multiple API versions simultaneously while maintaining backward compatibility.
What to check first
- Check your current API routes with
grep -r "@app.route\|@router" .(Flask/FastAPI) orgrep -r "app.get\|app.post" .(Express) to understand existing endpoint structure - Verify your framework version with
pip show flaskornpm list expressto ensure versioning features are available - Review your current request handling to identify where version detection logic should intercept requests
Steps
- Choose a versioning strategy: URL path (
/api/v1/users), query parameter (/api/users?version=1), header-based (X-API-Version: 1), or subdomain (v1.api.example.com) - Create a version detection middleware or decorator that extracts the version from the chosen location before routing
- Organize your endpoint files by version (e.g.,
routes/v1/users.py,routes/v2/users.py) or use version-aware route grouping - Implement version routing logic that maps incoming requests to the correct handler based on detected version
- Add version deprecation tracking—store when each version will sunset and return
Deprecationheaders warning clients - Create response schema versioning to handle data transformation between versions when needed
- Write integration tests for each version to ensure endpoints behave as expected and old versions don't break
- Document the API versioning policy (how long versions are supported, deprecation timeline) in your API docs
Code
# API Versioning Strategy - URL Path + Header Fallback (Flask/FastAPI)
from flask import Flask, request, jsonify, Blueprint
from functools import wraps
from datetime import datetime
from typing import Optional, Dict, Any
app = Flask(__name__)
# Version metadata
API_VERSIONS = {
"1": {"status": "deprecated", "sunset_date": "2025-06-01"},
"2": {"status": "current", "sunset_date": None},
"3": {"status": "beta", "sunset_date": None},
}
# Supported version transformations
SCHEMA_TRANSFORMS = {
"1->2": lambda data: {**data, "created_at": data.get("timestamp")},
"2->1": lambda data: {**data, "timestamp": data.get("created_at")},
}
def detect_api_version(f):
"""Middleware decorator to extract and validate API version."""
@wraps(f)
def decorated_function(*args, **kwargs):
version = None
# Priority: URL path > Header > Default
if 'version' in kwargs:
version = kwargs.pop('version')
elif 'X-API-Version' in request.headers:
version = request.headers.get('X-API-Version')
else:
version = '2'
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Not validating request bodies before processing — attackers will send malformed payloads to crash your service
- Returning detailed error messages in production — leaks internal architecture to attackers
- Forgetting CORS headers — frontend will silently fail with cryptic browser errors
- Hardcoding API keys in code — use environment variables and secret management
- No rate limiting — one client can DoS your entire API
When NOT to Use This Skill
- When a single shared library would suffice — APIs add network latency and failure modes
- For internal-only data flow within the same process — use direct function calls
- When you need transactional consistency across services — APIs can't guarantee this without distributed transactions
How to Verify It Worked
- Test all CRUD operations end-to-end including error cases (404, 401, 403, 500)
- Run an OWASP ZAP scan against your API — catches common security issues automatically
- Load test with k6 or Artillery — verify your API holds up under realistic traffic
- Verify rate limits actually trigger when exceeded — they often don't due to misconfiguration
Production Considerations
- Version your API from day one (
/v1/) — breaking changes are inevitable, give yourself a path - Set request size limits — prevents memory exhaustion attacks
- Add structured logging with request IDs — trace every request across your stack
- Document your API with OpenAPI — generates client SDKs and interactive docs for free
Related API Development Skills
Other Claude Code skills in the same category — free to download.
REST API Scaffold
Scaffold a complete REST API with CRUD operations
GraphQL Schema Generator
Generate GraphQL schema from existing data models
API Documentation
Generate OpenAPI/Swagger documentation from code
Rate Limiter
Add rate limiting to API endpoints
API Error Handler
Create standardized API error handling
Request Validator
Add request validation middleware (Zod, Joi)
API Response Formatter
Standardize API response format
Webhook Handler
Create webhook endpoint with signature verification
Want a API Development skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.