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