Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
API Developmentintermediate

API Versioning

Share

Implement API versioning strategy

Works with OpenClaude

You 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) or grep -r "app.get\|app.post" . (Express) to understand existing endpoint structure
  • Verify your framework version with pip show flask or npm list express to ensure versioning features are available
  • Review your current request handling to identify where version detection logic should intercept requests

Steps

  1. 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)
  2. Create a version detection middleware or decorator that extracts the version from the chosen location before routing
  3. Organize your endpoint files by version (e.g., routes/v1/users.py, routes/v2/users.py) or use version-aware route grouping
  4. Implement version routing logic that maps incoming requests to the correct handler based on detected version
  5. Add version deprecation tracking—store when each version will sunset and return Deprecation headers warning clients
  6. Create response schema versioning to handle data transformation between versions when needed
  7. Write integration tests for each version to ensure endpoints behave as expected and old versions don't break
  8. 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

Quick Info

Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
apiversioningstrategy

Install command:

curl -o ~/.claude/skills/api-versioning.md https://claude-skills-hub.vercel.app/skills/api/api-versioning.md

Related API Development Skills

Other Claude Code skills in the same category — free to download.

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.