Modern QA2026Drift Prevention: Schema Validation Middleware — tiles
Log inJoin
82 / 89 · 04 API & Contract Testing with AI · Schema Drift Detection← prev⊞ allnext →☰ Read as one page

12.6Drift Prevention: Schema Validation Middleware

The best way to prevent drift is to validate responses against the schema at runtime:

# Express.js middleware example
from openapi_core import OpenAPI
from openapi_core.validation.response import V31ResponseValidator

class SchemaValidationMiddleware:
    """Validate every API response against the OpenAPI schema."""

    def __init__(self, spec_path: str, enforce: bool = False):
        self.openapi = OpenAPI.from_file_path(spec_path)
        self.enforce = enforce  # True = block invalid responses

    def validate_response(self, request, response):
        result = self.openapi.validate_response(request, response)

        if result.errors:
            for error in result.errors:
                logger.warning(f"Schema drift detected: {error}")

            if self.enforce:
                return {"error": "Response does not match API schema"}, 500

        return response

Run this middleware in staging (enforce=False, log only) to continuously detect drift without impacting production.