一键导入
api-versioning
Implement API versioning strategies for backward compatibility. Covers URL versioning, header versioning, and deprecation workflows.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Implement API versioning strategies for backward compatibility. Covers URL versioning, header versioning, and deprecation workflows.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Multi-turn conversational AI for intent extraction, clarification, and generation readiness detection. Guides users through articulating creative intent with structured parameter extraction.
External AI API integration with retry logic, rate limiting, content safety detection, and multi-turn conversation support for image generation.
Real-time analytics with Redis counters, periodic PostgreSQL flush, and time-series aggregation. High-performance event tracking without database bottlenecks.
Rule-based anomaly detection for production systems with configurable thresholds, cooldown periods to prevent alert storms, and error pattern tracking for repeated failures.
Centralized TypeScript API client with typed namespaces, automatic token refresh with request deduplication, TanStack Query integration, and consistent error handling.
Two-phase commit matchmaking that verifies both player connections before creating a match. Handles disconnections gracefully with automatic re-queue of healthy players.
| name | api-versioning |
| description | Implement API versioning strategies for backward compatibility. Covers URL versioning, header versioning, and deprecation workflows. |
| license | MIT |
| compatibility | TypeScript/JavaScript, Python |
| metadata | {"category":"api","time":"3h","source":"drift-masterguide"} |
Evolve your API without breaking existing clients.
GET /api/v1/users
GET /api/v2/users
Pros: Clear, cacheable, easy to route Cons: URL pollution
GET /api/users
Accept: application/vnd.myapp.v2+json
Pros: Clean URLs Cons: Harder to test, not cacheable by URL
GET /api/users?version=2
Pros: Simple Cons: Easy to forget, caching issues
// version-router.ts
import { Router, Request, Response, NextFunction } from 'express';
type VersionHandler = (req: Request, res: Response, next: NextFunction) => void;
interface VersionedRoute {
v1?: VersionHandler;
v2?: VersionHandler;
v3?: VersionHandler;
default: VersionHandler;
}
class VersionRouter {
private router = Router();
private currentVersion = 'v2';
private supportedVersions = ['v1', 'v2'];
private deprecatedVersions = ['v1'];
constructor() {
// Add version detection middleware
this.router.use(this.detectVersion.bind(this));
}
private detectVersion(req: Request, res: Response, next: NextFunction) {
// Extract version from URL path
const match = req.path.match(/^\/v(\d+)\//);
if (match) {
req.apiVersion = `v${match[1]}`;
} else {
req.apiVersion = this.currentVersion;
}
// Check if version is supported
if (!this.supportedVersions.includes(req.apiVersion)) {
return res.status(400).json({
error: 'Unsupported API version',
supportedVersions: this.supportedVersions,
});
}
// Add deprecation warning header
if (this.deprecatedVersions.includes(req.apiVersion)) {
res.setHeader('Deprecation', 'true');
res.setHeader('Sunset', '2025-01-01');
res.setHeader('Link', '</api/v2>; rel="successor-version"');
}
next();
}
versioned(path: string, handlers: VersionedRoute) {
this.router.all(path, (req: Request, res: Response, next: NextFunction) => {
const version = req.apiVersion as keyof VersionedRoute;
const handler = handlers[version] || handlers.default;
handler(req, res, next);
});
}
getRouter() {
return this.router;
}
}
// Extend Express Request type
declare global {
namespace Express {
interface Request {
apiVersion?: string;
}
}
}
export { VersionRouter };
// routes/users.ts
import { VersionRouter } from './version-router';
const versionRouter = new VersionRouter();
// Different implementations per version
versionRouter.versioned('/users', {
v1: async (req, res) => {
// V1: Returns flat user object
const users = await db.users.findMany();
res.json(users.map(u => ({
id: u.id,
name: u.name,
email: u.email,
})));
},
v2: async (req, res) => {
// V2: Returns nested structure with metadata
const users = await db.users.findMany({ include: { profile: true } });
res.json({
data: users.map(u => ({
id: u.id,
attributes: {
name: u.name,
email: u.email,
profile: u.profile,
},
})),
meta: { total: users.length },
});
},
default: async (req, res) => {
// Default to latest
res.redirect(307, `/api/v2${req.path}`);
},
});
export const userRoutes = versionRouter.getRouter();
// header-version-middleware.ts
function headerVersionMiddleware(req: Request, res: Response, next: NextFunction) {
const acceptHeader = req.headers.accept || '';
// Parse: application/vnd.myapp.v2+json
const match = acceptHeader.match(/application\/vnd\.myapp\.v(\d+)\+json/);
if (match) {
req.apiVersion = `v${match[1]}`;
} else {
req.apiVersion = 'v2'; // Default
}
next();
}
# version_router.py
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import JSONResponse
from typing import Callable, Dict
class VersionedRouter:
def __init__(self):
self.router = APIRouter()
self.current_version = "v2"
self.supported_versions = ["v1", "v2"]
self.deprecated_versions = ["v1"]
def versioned_route(
self,
path: str,
methods: list[str],
handlers: Dict[str, Callable],
):
async def route_handler(request: Request):
# Extract version from path
version = self._extract_version(request.url.path)
if version not in self.supported_versions:
raise HTTPException(
status_code=400,
detail=f"Unsupported version. Supported: {self.supported_versions}"
)
handler = handlers.get(version, handlers.get("default"))
if not handler:
raise HTTPException(status_code=404)
response = await handler(request)
# Add deprecation headers
if version in self.deprecated_versions:
response.headers["Deprecation"] = "true"
response.headers["Sunset"] = "2025-01-01"
return response
for method in methods:
self.router.add_api_route(path, route_handler, methods=[method])
def _extract_version(self, path: str) -> str:
import re
match = re.search(r"/v(\d+)/", path)
return f"v{match.group(1)}" if match else self.current_version
# routes/users.py
from version_router import VersionedRouter
router = VersionedRouter()
async def get_users_v1(request: Request):
users = await db.users.find_many()
return JSONResponse([{"id": u.id, "name": u.name} for u in users])
async def get_users_v2(request: Request):
users = await db.users.find_many(include={"profile": True})
return JSONResponse({
"data": [{"id": u.id, "attributes": {"name": u.name}} for u in users],
"meta": {"total": len(users)},
})
router.versioned_route(
"/users",
methods=["GET"],
handlers={
"v1": get_users_v1,
"v2": get_users_v2,
"default": get_users_v2,
},
)
// Add to all v1 responses
res.setHeader('Deprecation', 'true');
res.setHeader('Sunset', '2025-06-01T00:00:00Z');
res.setHeader('Link', '</api/v2/docs>; rel="successor-version"');
// Track v1 usage for migration planning
if (req.apiVersion === 'v1') {
metrics.increment('api.v1.requests', {
endpoint: req.path,
client: req.headers['x-client-id'],
});
}
// Phase 1: Warnings (3 months)
// Phase 2: Rate limit v1 (1 month)
if (req.apiVersion === 'v1') {
await rateLimiter.consume(req.ip, { points: 10 }); // 10x cost
}
// Phase 3: Return 410 Gone
if (req.apiVersion === 'v1' && Date.now() > SUNSET_DATE) {
return res.status(410).json({
error: 'API version v1 has been sunset',
migration: 'https://docs.example.com/v2-migration',
});
}
// V1 Response (flat)
{
"id": "123",
"name": "John",
"email": "john@example.com"
}
// V2 Response (JSON:API style)
{
"data": {
"id": "123",
"type": "user",
"attributes": {
"name": "John",
"email": "john@example.com"
}
},
"meta": {
"version": "v2"
}
}