v0.166.0
 1from typing import Any
 2
 3
 4class OpenAPIValidationError(Exception):
 5    """Raised when an OpenAPI schema fails structural validation."""
 6
 7
 8def validate_openapi_schema(schema: dict[str, Any]) -> None:
 9    """Validate a generated OpenAPI document against the OpenAPI specification.
10
11    Uses ``openapi-spec-validator`` to detect the spec version (3.0.x or 3.1.x)
12    and run the appropriate JSON Schema validation locally — no network calls.
13    """
14    try:
15        from openapi_spec_validator import validate
16        from openapi_spec_validator.validation.exceptions import (
17            OpenAPIValidationError as _UpstreamValidationError,
18        )
19        from referencing.exceptions import Unresolvable
20    except ImportError as exc:
21        raise OpenAPIValidationError(
22            "openapi-spec-validator is required for --validate. "
23            "Install it with: pip install openapi-spec-validator"
24        ) from exc
25
26    try:
27        validate(schema)
28    except (_UpstreamValidationError, Unresolvable) as exc:
29        raise OpenAPIValidationError(str(exc)) from exc