### Install openapi-spec-validator Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Install the library using pip. Optionally, install the faster Rust-based JSON Schema backend for improved performance. ```bash pip install openapi-spec-validator # Optional: install faster Rust-based JSON Schema backend pip install jsonschema-rs ``` -------------------------------- ### Install jsonschema-rs for Backend Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/README.rst Install the optional `jsonschema-rs` package if you intend to use it as the schema validator backend for improved performance. ```bash pip install jsonschema-rs ``` -------------------------------- ### Install openapi-spec-validator from Source Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/index.md Install the package in editable mode directly from the source repository. ```bash pip install -e git+https://github.com/python-openapi/openapi-spec-validator.git#egg=openapi_spec_validator ``` -------------------------------- ### Install Development Dependencies with Poetry Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Installs all development dependencies, including dev and docs extras, using Poetry. ```bash poetry install --with dev ``` ```bash poetry install --with docs ``` -------------------------------- ### Install dependencies with Poetry Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/CONTRIBUTING.rst Install the project's runtime and development dependencies using Poetry. This command should be run after setting up the development environment. ```console poetry install ``` -------------------------------- ### Install openapi-spec-validator via Pip Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/index.md Use this command to install the package using pip and PyPI. ```bash pip install openapi-spec-validator ``` -------------------------------- ### Install and Run pre-commit hook Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Commands to install the pre-commit hooks locally and run the OpenAPI spec validator manually against all files. ```bash # Install hooks into the local git repo pre-commit install ``` ```bash # Run manually against all OpenAPI files pre-commit run openapi-spec-validator --all-files ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/CONTRIBUTING.rst Install pre-commit to enable automatic code checks before committing. This ensures code quality and consistency. ```console pre-commit install ``` -------------------------------- ### CLI - openapi-spec-validator Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt The installed CLI entry-point validates one or more files. Exit code `0` = valid, `1` = validation error, `2` = read/parse error. ```APIDOC ## CLI — `openapi-spec-validator` The installed CLI entry-point validates one or more files. Exit code `0` = valid, `1` = validation error, `2` = read/parse error. ```bash # Validate a single file (version auto-detected) openapi-spec-validator openapi.yaml # openapi.yaml: OK # Pin to a specific OpenAPI version openapi-spec-validator --schema 3.1 openapi.yaml # Report ALL validation errors (default: first only) openapi-spec-validator --validation-errors all openapi.yaml # Show all subschema error details (default: best-match) openapi-spec-validator --validation-errors all --subschema-errors all openapi.yaml # Validate multiple files at once openapi-spec-validator v2/swagger.yaml v3/openapi.yaml # Pipe via stdin cat openapi.yaml | openapi-spec-validator - # Via Python module python -m openapi_spec_validator openapi.yaml ``` ``` -------------------------------- ### Iterate Over All Validation Errors with OpenAPIV32SpecValidator Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Instantiate a concrete validator class to iterate over all validation errors, useful for comprehensive error reporting in CI pipelines. This example demonstrates finding duplicate operation IDs and missing required properties. ```python from openapi_spec_validator import OpenAPIV32SpecValidator spec = { "openapi": "3.2.0", "info": {"title": "Broken API"}, # missing 'version' "paths": { "/a": {"get": {"operationId": "op1", "responses": {}}}, "/b": {"get": {"operationId": "op1", "responses": {}}}, # duplicate operationId }, } validator = OpenAPIV32SpecValidator(spec) errors = list(validator.iter_errors()) for i, err in enumerate(errors, 1): print(f"[{i}] {err.message}") # [1] 'version' is a required property # [2] ...duplicate operationId 'op1'... # is_valid() returns False without raising print(validator.is_valid()) # False ``` -------------------------------- ### Validate OpenAPI Spec from File Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/python.md Reads an OpenAPI specification from a file and validates it. If no exception is raised, the spec is considered valid. An example of an invalid spec is shown, which raises an `OpenAPIValidationError`. ```python from openapi_spec_validator import validate from openapi_spec_validator.readers import read_from_filename spec_dict, base_uri = read_from_filename('openapi.yaml') # If no exception is raised by validate(), the spec is valid. validate(spec_dict) # Example of an intentionally invalid spec. invalid_spec = {'openapi': '3.1.0'} validate(invalid_spec) Traceback ( ...) OpenAPIValidationError: 'info' is a required property ``` -------------------------------- ### Explicit Versioned Validator Classes Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Import and use specific validator classes to enforce a particular OpenAPI version, overriding any version declared within the spec itself. This example shows validation with `OpenAPIV2SpecValidator`, `OpenAPIV30SpecValidator`, `OpenAPIV31SpecValidator`, and `OpenAPIV32SpecValidator`. ```python from openapi_spec_validator import ( OpenAPIV2SpecValidator, OpenAPIV30SpecValidator, OpenAPIV31SpecValidator, OpenAPIV32SpecValidator, OpenAPIV3SpecValidator, # alias for the latest v3 validate, ) swagger_spec = { "swagger": "2.0", "info": {"title": "Pet Store", "version": "1.0"}, "paths": {}, } oas3_spec = { "openapi": "3.2.0", "info": {"title": "Pet Store", "version": "1.0"}, "paths": {}, } # Explicit class passed to validate() validate(swagger_spec, cls=OpenAPIV2SpecValidator) validate(oas3_spec, cls=OpenAPIV32SpecValidator) validate(oas3_spec, cls=OpenAPIV3SpecValidator) # same as V32 # Instantiate and call validate() directly OpenAPIV31SpecValidator(oas3_spec).validate() # raises: wrong version declared # Iterate errors with a specific class for err in OpenAPIV30SpecValidator(oas3_spec).iter_errors(): print(err.message) ``` -------------------------------- ### Build Documentation with Sphinx Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Builds HTML documentation using Sphinx, enabling warnings as errors and detailed output. ```bash poetry run python -m sphinx -T -b html -d docs/_build/doctrees -D language=en docs docs/_build/html -n -W ``` -------------------------------- ### Build Project Artifacts with Poetry Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Creates distribution artifacts (sdist and wheel) for the project using Poetry. ```bash poetry build ``` -------------------------------- ### Configure Poetry to use virtual environments in project Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/CONTRIBUTING.rst Configure Poetry to create virtual environments within the project directory. This is recommended for managing project dependencies. ```console poetry config virtualenvs.in-project true ``` -------------------------------- ### Run pre-commit checks on all files Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/CONTRIBUTING.rst Run all configured pre-commit checks on every file in the repository. This is useful for a comprehensive check of the entire codebase. ```console pre-commit run --all-files ``` -------------------------------- ### OpenAPI Spec Validator CLI Help Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/cli.md Display the help message for the openapi-spec-validator command-line tool, showing available options and arguments. ```text usage: openapi-spec-validator [-h] [--subschema-errors {best-match,all}] [--validation-errors {first,all}] [--errors {best-match,all}] [--schema {detect,2.0,3.0,3.1,3.2}] [--version] file [file ...] positional arguments: file Validate specified file(s). options: -h, --help show this help message and exit --subschema-errors {best-match,all} Control subschema error details. Defaults to "best-match", use "all" to get all subschema errors. --validation-errors {first,all} Control validation errors count. Defaults to "first", use "all" to get all validation errors. --errors {best-match,all}, --error {best-match,all} Deprecated alias for --subschema-errors. --schema {detect,2.0,3.0,3.1,3.2} OpenAPI schema version (default: detect). --version show program's version number and exit ``` -------------------------------- ### Show All Validation Errors with Docker Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/cli.md Use Docker to run the validator and display all validation errors. ```bash docker run -v path/to/openapi.yaml:/openapi.yaml --rm pythonopenapi/openapi-spec-validator --validation-errors all /openapi.yaml ``` -------------------------------- ### Tune openapi-spec-validator Performance with Environment Variables Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/README.rst Configure performance tuning options using environment variables. Adjust the resolved-path cache size or select the schema validator backend. ```bash OPENAPI_SPEC_VALIDATOR_RESOLVED_CACHE_MAXSIZE=2048 ``` ```bash OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND=jsonschema-rs ``` -------------------------------- ### Format Code with Black and Isort Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Applies code formatting using Black and sorts imports with Isort. ```bash poetry run black . && poetry run isort . ``` -------------------------------- ### Run Full Test Suite with Pytest Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes the complete test suite using Poetry and Pytest. ```bash poetry run pytest ``` -------------------------------- ### Activate Poetry shell Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/CONTRIBUTING.rst Activate the virtual environment created by Poetry to work within the project's isolated environment. This command makes project-specific packages available. ```console poetry shell ``` -------------------------------- ### Legacy Build Artifacts Command Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Builds project artifacts using a legacy Makefile target. ```bash make dist-build ``` -------------------------------- ### Run pre-commit checks on staged files Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/CONTRIBUTING.rst Execute all configured pre-commit checks on the currently staged files. This is useful for verifying changes before committing. ```console pre-commit run ``` -------------------------------- ### Run Multi-Python Matrix Tests with Tox Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes tests across multiple Python versions using Tox. ```bash tox ``` -------------------------------- ### Configure openapi-spec-validator Settings Programmatically Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Set environment variables in Python to configure the validator's cache size and schema validator backend. Settings are read on instantiation. ```python import os os.environ["OPENAPI_SPEC_VALIDATOR_RESOLVED_CACHE_MAXSIZE"] = "512" os.environ["OPENAPI_SPEC_VALIDATOR_SCHEMA_VALIDATOR_BACKEND"] = "jsonschema-rs" # Settings are read fresh on each instantiation via pydantic-settings from openapi_spec_validator.settings import OpenAPISpecValidatorSettings s = OpenAPISpecValidatorSettings() print(s.resolved_cache_maxsize) # 512 print(s.schema_validator_backend) # jsonschema-rs ``` -------------------------------- ### Check Dependencies with Deptry Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Analyzes project dependencies for unused or missing packages using Deptry. ```bash poetry run deptry . ``` -------------------------------- ### Show All Validation and Subschema Errors with Docker Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/cli.md Run the validator via Docker to show all validation errors and detailed subschema errors. ```bash docker run -v path/to/openapi.yaml:/openapi.yaml --rm pythonopenapi/openapi-spec-validator --validation-errors all --subschema-errors all /openapi.yaml ``` -------------------------------- ### CLI: Validate OpenAPI Specification Files Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Command-line interface for validating OpenAPI specification files. Supports single file validation, pinning to specific versions, reporting all errors, and processing multiple files. ```bash # Validate a single file (version auto-detected) openapi-spec-validator openapi.yaml # openapi.yaml: OK # Pin to a specific OpenAPI version openapi-spec-validator --schema 3.1 openapi.yaml # Report ALL validation errors (default: first only) openapi-spec-validator --validation-errors all openapi.yaml # Show all subschema error details (default: best-match) openapi-spec-validator --validation-errors all --subschema-errors all openapi.yaml # Validate multiple files at once openapi-spec-validator v2/swagger.yaml v3/openapi.yaml # Pipe via stdin cat openapi.yaml | openapi-spec-validator - # Via Python module python -m openapi_spec_validator openapi.yaml ``` -------------------------------- ### Lint Code with Flake8 Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Runs the Flake8 linter to check for code style and potential errors. ```bash poetry run flake8 ``` -------------------------------- ### Configure openapi-spec-validator Pre-commit Hook Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/hook.md Add this configuration to your .pre-commit-config.yaml file to enable the openapi-spec-validator hook. Specify the repository and the desired revision (version or 'master'). ```yaml repos: - repo: https://github.com/python-openapi/openapi-spec-validator rev: 0.8.5 # The version to use or 'master' for latest hooks: - id: openapi-spec-validator ``` -------------------------------- ### Validate OpenAPI Spec via Docker Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/index.md Run the validator using Docker, mounting your OpenAPI file into the container. ```bash docker run -v path/to/openapi.yaml:/openapi.yaml --rm pythonopenapi/openapi-spec-validator /openapi.yaml ``` ```bash docker run -v path/to/openapi.yaml:/openapi.yaml --rm pythonopenapi/openapi-spec-validator --validation-errors all /openapi.yaml ``` -------------------------------- ### Clean Build and Test Artifacts Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Removes generated build and test artifacts from the project directory using a Makefile target. ```bash make cleanup ``` -------------------------------- ### Handle OpenAPI Validation Errors in Python Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Demonstrates catching specific OpenAPI validation errors, such as missing 'info' or duplicate operation IDs, using try-except blocks and iterating over errors. ```python from openapi_spec_validator import validate, OpenAPIV30SpecValidator from openapi_spec_validator.validation.exceptions import ( OpenAPIValidationError, ValidatorDetectError, DuplicateOperationIDError, ParameterDuplicateError, ) # Catch the base class to handle any spec error try: validate({"openapi": "3.0.0"}) # missing 'info' except OpenAPIValidationError as e: print(type(e).__name__, e.message) # Catch the specific subclass for duplicate operation IDs spec = { "openapi": "3.0.0", "info": {"title": "API", "version": "1.0"}, "paths": { "/a": {"get": {"operationId": "same", "responses": {"200": {"description": "ok"}}}}, "/b": {"get": {"operationId": "same", "responses": {"200": {"description": "ok"}}}}, }, } for err in OpenAPIV30SpecValidator(spec).iter_errors(): if isinstance(err, DuplicateOperationIDError): print("Duplicate operationId:", err.message) ``` -------------------------------- ### Read Spec from Stdin and Validate Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Reads OpenAPI specification content from standard input and validates it. Use '-' as the filename to indicate stdin. ```python from openapi_spec_validator import validate from openapi_spec_validator.readers import read_from_stdin # when sys.stdin already contains spec content: spec_dict, base_uri = read_from_stdin("-") validate(spec_dict) ``` ```bash # Equivalent CLI usage cat openapi.yaml | openapi-spec-validator - ``` -------------------------------- ### read_from_filename(filename) Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Loads an OpenAPI specification from a local file. It resolves the file path, converts it to a file:// URI, and returns the parsed spec dictionary along with the base URI, which is crucial for resolving relative references. ```APIDOC ## read_from_filename(filename) ### Description Resolves the file to an absolute path, converts it to a `file://` URI (needed for `$ref` resolution), and returns the parsed spec dict together with the base URI. ### Parameters - **filename** (str) - The path to the OpenAPI specification file. ### Returns - **tuple** - A tuple containing the spec dictionary and its base URI. ### Request Example ```python from openapi_spec_validator.readers import read_from_filename from openapi_spec_validator import validate # Returns (spec_dict, base_uri) spec_dict, base_uri = read_from_filename("openapi.yaml") # base_uri is required so that $ref: './schemas/pet.yaml' resolves correctly validate(spec_dict, base_uri=base_uri) # OSError is raised when the file does not exist try: read_from_filename("missing.yaml") except OSError as e: print(e) # No such file: missing.yaml ``` ``` -------------------------------- ### Validate OpenAPI Spec using Python Module Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/index.md Execute the validator as a Python module from the command line. ```bash python -m openapi_spec_validator openapi.yaml ``` -------------------------------- ### Integrate openapi-spec-validator with pre-commit Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Configure a .pre-commit-config.yaml file to use the openapi-spec-validator hook. This prevents commits with invalid OpenAPI specifications. ```yaml # .pre-commit-config.yaml repos: - repo: https://github.com/python-openapi/openapi-spec-validator rev: 0.8.5 # pin to a release tag, or use 'master' for latest hooks: - id: openapi-spec-validator ``` -------------------------------- ### Validate OpenAPI Spec via CLI Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/README.rst Use the command-line interface to validate an OpenAPI specification file. Supports direct file input, piping from stdin, and Docker execution. ```bash openapi-spec-validator openapi.yaml ``` ```bash cat openapi.yaml | openapi-spec-validator - ``` ```bash docker run -v path/to/openapi.yaml:/openapi.yaml --rm pythonopenapi/openapi-spec-validator /openapi.yaml ``` ```bash python -m openapi_spec_validator openapi.yaml ``` -------------------------------- ### Iterate Through Validation Errors Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/python.md Shows how to create an iterator to go through all validation errors found in an OpenAPI specification. ```python from openapi_spec_validator import OpenAPIV32SpecValidator errors_iterator = OpenAPIV32SpecValidator(spec).iter_errors() ``` -------------------------------- ### Check Code Formatting with Black and Isort Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Checks if code adheres to Black and Isort formatting rules without modifying files. ```bash poetry run black --check . && poetry run isort --check-only . ``` -------------------------------- ### Run Pytest on a Specific File Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes Pytest only on the specified integration test file. ```bash poetry run pytest tests/integration/test_main.py ``` -------------------------------- ### Fast Pytest Execution without Default Addopts Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Runs a specific test file and function with Pytest, disabling default addopts like coverage and junit reporting. ```bash poetry run pytest -o addopts='' tests/integration/test_main.py::test_version ``` -------------------------------- ### Run Pytest on a Parametrized Test Case Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes a specific parametrized test case in Pytest. ```bash poetry run pytest 'tests/integration/validation/test_validators.py::TestLocalOpenAPIv30Validator::test_valid[petstore.yaml]' ``` -------------------------------- ### validate_url(spec_url, cls=None) Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Fetches an OpenAPI specification from a URL (HTTP, HTTPS, or file://) and validates it. An optional validator class can be provided to enforce a specific OpenAPI version. ```APIDOC ## validate_url(spec_url, cls=None) ### Description Fetches the spec over HTTP(S) or from a `file://` URI and validates it. Accepts an optional `cls` to pin the OpenAPI version. ### Parameters - **spec_url** (str) - The URL of the OpenAPI specification to validate. - **cls** (type, optional) - A specific validator class to use, bypassing auto-detection. Defaults to None. ### Request Example ```python from openapi_spec_validator import validate_url from openapi_spec_validator import OpenAPIV30SpecValidator from openapi_spec_validator.validation.exceptions import OpenAPIValidationError # Auto-detect version from a remote spec validate_url("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/f75f8486a1aae1a7ceef92fbc63692cb2556c0cd/examples/v3.0/petstore.yaml") # Pin to OpenAPI 3.0 validate_url( "https://example.com/openapi.json", cls=OpenAPIV30SpecValidator, ) # Validate a local file via file:// URI from pathlib import Path uri = Path("/path/to/openapi.yaml").as_uri() try: validate_url(uri) print("Valid!") except OpenAPIValidationError as e: print(f"Invalid: {e.message}") ``` ``` -------------------------------- ### Validate OpenAPI Spec via CLI Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/index.md Use the command-line interface to validate an OpenAPI specification file. ```bash openapi-spec-validator openapi.yaml ``` ```bash cat openapi.yaml | openapi-spec-validator - ``` -------------------------------- ### Load OpenAPI Spec from File Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt The `read_from_filename()` function loads an OpenAPI specification from a file, resolves it to an absolute path, and converts it to a `file://` URI. This base URI is crucial for correctly resolving relative `$ref` paths within the specification. It returns the parsed spec dictionary and the base URI. ```python from openapi_spec_validator.readers import read_from_filename from openapi_spec_validator import validate # Returns (spec_dict, base_uri) spec_dict, base_uri = read_from_filename("openapi.yaml") # base_uri is required so that $ref: './schemas/pet.yaml' resolves correctly validate(spec_dict, base_uri=base_uri) # OSError is raised when the file does not exist try: read_from_filename("missing.yaml") except OSError as e: print(e) # No such file: missing.yaml ``` -------------------------------- ### Check Types with Mypy Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Performs static type checking using Mypy. ```bash poetry run mypy ``` -------------------------------- ### Validate OpenAPI Spec via Pipe Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/cli.md Pipe the content of an OpenAPI specification file to the validator. ```bash cat openapi.yaml | openapi-spec-validator - ``` -------------------------------- ### Validate OpenAPI Spec Directly Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/cli.md Use this command to validate an OpenAPI specification file directly. ```bash openapi-spec-validator openapi.yaml ``` -------------------------------- ### Load OpenAPI Spec from Stdin Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt The `read_from_stdin()` function reads a YAML or JSON OpenAPI specification piped into the process. This function is typically used internally by the CLI when the input filename is specified as `-`. ```python import sys from openapi_spec_validator.readers import read_from_stdin from openapi_spec_validator import validate # Typically called by the CLI; can also be used programmatically ``` -------------------------------- ### get_spec_version(spec) - Detect the OpenAPI version of a spec Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Returns a `SpecVersion` dataclass (`keyword`, `major`, `minor`) describing the detected version. Raises `OpenAPIVersionNotFound` if the spec does not match any known version. ```APIDOC ## `get_spec_version(spec)` — Detect the OpenAPI version of a spec Returns a `SpecVersion` dataclass (`keyword`, `major`, `minor`) describing the detected version. Raises `OpenAPIVersionNotFound` if the spec does not match any known version. ```python from openapi_spec_validator.versions.shortcuts import get_spec_version from openapi_spec_validator.versions.exceptions import OpenAPIVersionNotFound swagger_spec = {"swagger": "2.0", "info": {"title": "Old API", "version": "1.0"}, "paths": {}} oas31_spec = {"openapi": "3.1.0", "info": {"title": "New API", "version": "1.0"}, "paths": {}} v2 = get_spec_version(swagger_spec) print(v2) # OpenAPIV2.0 print(v2.keyword) # swagger print(v2.major) # 2 print(v2.minor) # 0 v31 = get_spec_version(oas31_spec) print(v31) # OpenAPIV3.1 try: get_spec_version({}) except OpenAPIVersionNotFound: print("Version not found") ``` ``` -------------------------------- ### Detect OpenAPI Version with get_spec_version Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Automatically detect the OpenAPI version of a specification dictionary. Raises `OpenAPIVersionNotFound` if the version cannot be determined. ```python from openapi_spec_validator.versions.shortcuts import get_spec_version from openapi_spec_validator.versions.exceptions import OpenAPIVersionNotFound swagger_spec = {"swagger": "2.0", "info": {"title": "Old API", "version": "1.0"}, "paths": {}} oas31_spec = {"openapi": "3.1.0", "info": {"title": "New API", "version": "1.0"}, "paths": {}} v2 = get_spec_version(swagger_spec) print(v2) # OpenAPIV2.0 print(v2.keyword) # swagger print(v2.major) # 2 print(v2.minor) # 0 v31 = get_spec_version(oas31_spec) print(v31) # OpenAPIV3.1 try: get_spec_version({}) except OpenAPIVersionNotFound: print("Version not found") ``` -------------------------------- ### Validate OpenAPI Spec Programmatically in Python Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/README.rst Use the Python package to validate OpenAPI specifications. Import the `validate` function and `read_from_filename` reader. Exceptions are raised for invalid specifications. ```python from openapi_spec_validator import validate from openapi_spec_validator.readers import read_from_filename spec_dict, base_uri = read_from_filename('openapi.yaml') # If no exception is raised by validate(), the spec is valid. validate(spec_dict) # Example of an intentionally invalid spec. invalid_spec = {'openapi': '3.1.0'} validate(invalid_spec) Traceback (most recent call last): ... OpenAPIValidationError: 'info' is a required property ``` -------------------------------- ### read_from_stdin() Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Reads an OpenAPI specification from standard input (stdin). This function is typically used internally by the CLI when the input filename is specified as '-'. ```APIDOC ## read_from_stdin() ### Description Reads a YAML or JSON spec piped into the process. Used internally by the CLI when the filename argument is `-`. ### Request Example ```python import sys from openapi_spec_validator.readers import read_from_stdin from openapi_spec_validator import validate # Typically called by the CLI; can also be used programmatically # Example: cat openapi.yaml | python your_script.py spec_dict, base_uri = read_from_stdin() validate(spec_dict, base_uri=base_uri) ``` ``` -------------------------------- ### Explicitly Specify Validator Class Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/python.md Demonstrates how to explicitly specify the validator class (e.g., `OpenAPIV32SpecValidator`) when validating a spec, allowing for precise version control. ```python validate(spec_dict, cls=OpenAPIV32SpecValidator) ``` -------------------------------- ### Run Only Network Tests with Pytest Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes Pytest, running only the tests marked with the 'network' marker. ```bash poetry run pytest -m network ``` -------------------------------- ### SpecValidator.iter_errors() - Iterate over all validation errors Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Instantiate any concrete validator class directly to iterate over every validation error instead of stopping at the first. Useful for CI pipelines that need a complete error report. ```APIDOC ## `SpecValidator.iter_errors()` — Iterate over all validation errors Instantiate any concrete validator class directly to iterate over every validation error instead of stopping at the first. Useful for CI pipelines that need a complete error report. ```python from openapi_spec_validator import OpenAPIV32SpecValidator spec = { "openapi": "3.2.0", "info": {"title": "Broken API"}, # missing 'version' "paths": { "/a": {"get": {"operationId": "op1", "responses": {}}}, "/b": {"get": {"operationId": "op1", "responses": {}}}, # duplicate operationId }, } validator = OpenAPIV32SpecValidator(spec) errors = list(validator.iter_errors()) for i, err in enumerate(errors, 1): print(f"[{i}] {err.message}") # [1] 'version' is a required property # [2] ...duplicate operationId 'op1'... # is_valid() returns False without raising print(validator.is_valid()) # False ``` ``` -------------------------------- ### Run Pytest by Keyword Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Filters Pytest execution to include only tests matching the specified keyword. ```bash poetry run pytest -k "schema_v31" ``` -------------------------------- ### Validate OpenAPI Spec in Python Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/index.md Use the Python package to read and validate an OpenAPI specification dictionary. ```python from openapi_spec_validator import validate_spec from openapi_spec_validator.readers import read_from_filename spec_dict, base_uri = read_from_filename('openapi.yaml') # If no exception is raised by validate_spec(), the spec is valid. validate_spec(spec_dict) validate_spec({'openapi': '3.1.0'}) ``` -------------------------------- ### Validate OpenAPI Spec from URL Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Use `validate_url()` to fetch and validate an OpenAPI specification directly from a URL (HTTP(S) or `file://`). An optional `cls` argument can be used to enforce a specific OpenAPI version. ```python from openapi_spec_validator import validate_url from openapi_spec_validator import OpenAPIV30SpecValidator from openapi_spec_validator.validation.exceptions import OpenAPIValidationError # Auto-detect version from a remote spec validate_url("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/" \ "f75f8486a1aae1a7ceef92fbc63692cb2556c0cd/examples/v3.0/petstore.yaml") # Pin to OpenAPI 3.0 validate_url( "https://example.com/openapi.json", cls=OpenAPIV30SpecValidator, ) # Validate a local file via file:// URI from pathlib import Path uri = Path("/path/to/openapi.yaml").as_uri() try: validate_url(uri) print("Valid!") except OpenAPIValidationError as e: print(f"Invalid: {e.message}") ``` -------------------------------- ### Boolean Validity Check with OpenAPIV30SpecValidator Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Use the `is_valid()` method for a simple pass/fail signal without raising exceptions. This is useful when only a boolean result is needed. ```python from openapi_spec_validator import OpenAPIV30SpecValidator valid_spec = { "openapi": "3.0.0", "info": {"title": "My API", "version": "0.1.0"}, "paths": {}, } invalid_spec = {"openapi": "3.0.0"} # missing 'info' v_valid = OpenAPIV30SpecValidator(valid_spec) v_invalid = OpenAPIV30SpecValidator(invalid_spec) print(v_valid.is_valid()) # True print(v_invalid.is_valid()) # False ``` -------------------------------- ### Run Pytest on a Specific Test Function Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes Pytest only on a single test function within a specified file. ```bash poetry run pytest tests/integration/test_main.py::test_version ``` -------------------------------- ### Run Pytest Excluding Network Tests Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/AGENTS.md Executes Pytest, excluding any tests marked with the 'network' marker. ```bash poetry run pytest -m "not network" ``` -------------------------------- ### Validate Spec with Base URI Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/python.md Validates an OpenAPI specification using a provided base URI, which is useful for specs with relative file references. ```python validate(spec_dict, base_uri='file:///path/to/spec/openapi.yaml') ``` -------------------------------- ### Validate OpenAPI Spec from URL Source: https://github.com/python-openapi/openapi-spec-validator/blob/master/docs/python.md Validates an OpenAPI specification directly from a URL. If no exception is raised, the spec is considered valid. ```python from openapi_spec_validator import validate_url # If no exception is raised by validate_url(), the spec is valid. validate_url('http://example.com/openapi.json') ``` -------------------------------- ### validate(spec, base_uri="", cls=None) Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Validates an OpenAPI specification dictionary. It auto-detects the OpenAPI version and raises an OpenAPIValidationError on the first error found. You can optionally specify a validator class to enforce a specific version or provide a base_uri for resolving relative references. ```APIDOC ## validate(spec, base_uri="", cls=None) ### Description Auto-detects OpenAPI version from the spec dict and raises `OpenAPIValidationError` on the first error found. Pass `cls` to bypass auto-detection and enforce a specific version. Pass `base_uri` to enable resolution of relative `$ref` file paths. ### Parameters - **spec** (dict) - The OpenAPI specification dictionary to validate. - **base_uri** (str, optional) - The base URI for resolving relative `$ref` paths. Defaults to "". - **cls** (type, optional) - A specific validator class to use, bypassing auto-detection. Defaults to None. ### Request Example ```python from openapi_spec_validator import validate from openapi_spec_validator import OpenAPIV31SpecValidator from openapi_spec_validator.validation.exceptions import OpenAPIValidationError, ValidatorDetectError # --- Valid OpenAPI 3.1 spec (auto-detected) --- spec = { "openapi": "3.1.0", "info": {"title": "Pet Store", "version": "1.0.0"}, "paths": { "/pets": { "get": { "summary": "List pets", "operationId": "listPets", "responses": {"200": {"description": "A list of pets"}}, } } }, } validate(spec) # No exception → spec is valid # --- Explicit validator class (skip auto-detection) --- validate(spec, cls=OpenAPIV31SpecValidator) # --- Spec with relative $refs: supply base_uri --- from openapi_spec_validator.readers import read_from_filename spec_dict, base_uri = read_from_filename("openapi.yaml") validate(spec_dict, base_uri=base_uri) # --- Invalid spec: missing required 'info' field --- try: validate({"openapi": "3.1.0"}) except OpenAPIValidationError as e: print(e.message) # 'info' is a required property # --- Unrecognised version raises ValidatorDetectError --- try: validate({}) except ValidatorDetectError: print("Could not detect OpenAPI version") ``` ``` -------------------------------- ### Validate OpenAPI Spec Dictionary Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Use the `validate()` function to validate an OpenAPI specification provided as a Python dictionary. It auto-detects the spec version or allows explicit version pinning using the `cls` argument. Provide `base_uri` to resolve relative `$ref` paths. ```python from openapi_spec_validator import validate from openapi_spec_validator import OpenAPIV31SpecValidator from openapi_spec_validator.validation.exceptions import OpenAPIValidationError, ValidatorDetectError # --- Valid OpenAPI 3.1 spec (auto-detected) --- spec = { "openapi": "3.1.0", "info": {"title": "Pet Store", "version": "1.0.0"}, "paths": { "/pets": { "get": { "summary": "List pets", "operationId": "listPets", "responses": {"200": {"description": "A list of pets"}}, } } }, } validate(spec) # No exception → spec is valid # --- Explicit validator class (skip auto-detection) --- validate(spec, cls=OpenAPIV31SpecValidator) # --- Spec with relative $refs: supply base_uri --- from openapi_spec_validator.readers import read_from_filename spec_dict, base_uri = read_from_filename("openapi.yaml") validate(spec_dict, base_uri=base_uri) # --- Invalid spec: missing required 'info' field --- try: validate({"openapi": "3.1.0"}) except OpenAPIValidationError as e: print(e.message) # 'info' is a required property # --- Unrecognised version raises ValidatorDetectError --- try: validate({}) except ValidatorDetectError: print("Could not detect OpenAPI version") ``` -------------------------------- ### SpecValidator.is_valid() - Boolean validity check Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Returns `True` if the spec is valid, `False` otherwise, without raising an exception. Useful when the calling code only needs a pass/fail signal. ```APIDOC ## `SpecValidator.is_valid()` — Boolean validity check Returns `True` if the spec is valid, `False` otherwise, without raising an exception. Useful when the calling code only needs a pass/fail signal. ```python from openapi_spec_validator import OpenAPIV30SpecValidator valid_spec = { "openapi": "3.0.0", "info": {"title": "My API", "version": "0.1.0"}, "paths": {}, } invalid_spec = {"openapi": "3.0.0"} # missing 'info' v_valid = OpenAPIV30SpecValidator(valid_spec) v_invalid = OpenAPIV30SpecValidator(invalid_spec) print(v_valid.is_valid()) # True print(v_invalid.is_valid()) # False ``` ``` -------------------------------- ### Explicit versioned validator classes Source: https://context7.com/python-openapi/openapi-spec-validator/llms.txt Import specific validator classes to enforce a particular OpenAPI version regardless of what the spec declares. ```APIDOC ## Explicit versioned validator classes Import specific validator classes to enforce a particular OpenAPI version regardless of what the spec declares. | Class | Validates | |---|---| | `OpenAPIV2SpecValidator` | Swagger / OpenAPI 2.0 | | `OpenAPIV30SpecValidator` | OpenAPI 3.0.x | | `OpenAPIV31SpecValidator` | OpenAPI 3.1.x | | `OpenAPIV32SpecValidator` | OpenAPI 3.2.x | | `OpenAPIV3SpecValidator` | Alias → `OpenAPIV32SpecValidator` | ```python from openapi_spec_validator import ( OpenAPIV2SpecValidator, OpenAPIV30SpecValidator, OpenAPIV31SpecValidator, OpenAPIV32SpecValidator, OpenAPIV3SpecValidator, # alias for the latest v3 validate, ) swagger_spec = { "swagger": "2.0", "info": {"title": "Pet Store", "version": "1.0"}, "paths": {}, } oas3_spec = { "openapi": "3.2.0", "info": {"title": "Pet Store", "version": "1.0"}, "paths": {}, } # Explicit class passed to validate() validate(swagger_spec, cls=OpenAPIV2SpecValidator) validate(oas3_spec, cls=OpenAPIV32SpecValidator) validate(oas3_spec, cls=OpenAPIV3SpecValidator) # same as V32 # Instantiate and call validate() directly OpenAPIV31SpecValidator(oas3_spec).validate() # raises: wrong version declared # Iterate errors with a specific class for err in OpenAPIV30SpecValidator(oas3_spec).iter_errors(): print(err.message) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.