"""Deprecation middleware for legacy API routes. Provides middleware to add deprecation warning headers to legacy /api/ routes during the transition to /api/v1/. """ import logging from datetime import datetime from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request logger = logging.getLogger(__name__) class DeprecationMiddleware(BaseHTTPMiddleware): """Middleware to add deprecation headers to legacy API routes. This middleware checks if a request is using a legacy /api/ route (instead of /api/v1/) and adds appropriate deprecation headers to encourage migration to the new versioned API. """ # Sunset date for legacy routes (6 months from now, adjust as needed) SUNSET_DATE = "2026-07-01T00:00:00Z" async def dispatch(self, request: Request, call_next): response = await call_next(request) # Check if this is a legacy /api/ route (not /api/v1/) path = request.url.path if path.startswith("/api/") and not path.startswith("/api/v1/"): # Skip deprecation headers for health check endpoints if path in ["/health", "/health/ready", "/health/live", "/health/detailed"]: return response # Add deprecation headers (RFC 8594) response.headers["Deprecation"] = "true" response.headers["Sunset"] = self.SUNSET_DATE response.headers["Link"] = f'; rel="successor-version"' response.headers["X-Deprecation-Notice"] = ( "This API endpoint is deprecated. " "Please migrate to /api/v1/ prefix. " f"This endpoint will be removed after {self.SUNSET_DATE}." ) return response