Swagger Spec Validator is a Python library that validates Swagger Specs against the Swagger 1.2 or Swagger 2.0 specification. The validator aims to check for full compliance with the Specification. It is currently in active maintenance, with version 3.0.4 released in June 2024.
pip install swagger-spec-validatorVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to validate a Swagger 2.0 specification using both a URL and a Python dictionary. It uses `validate_spec_url` for remote specifications and `validate_spec` for in-memory dictionary representations, which can be loaded from local YAML/JSON files using PyYAML.
Ensure your specification is Swagger 1.2 or 2.0. If using OpenAPI 3.x, switch to a compatible validator like `openapi-spec-validator`.
Pin the library version in your `requirements.txt` or `pyproject.toml` and review changelogs when upgrading.
Ensure network connectivity for URL validation or external references. For offline validation of `$ref` pointers, consider tools that bundle or dereference the spec first, or ensure all referenced schemas are local and resolvable within the provided spec dictionary.
Be aware of potential limitations when using complex JSON Schema constructs within Swagger specifications. Manual review or supplementary validation might be necessary for such cases.
For OpenAPI 3.x specifications, use a dedicated validator library like `openapi-spec-validator` or `pydantic-openapi-spec`. Ensure your input specification is Swagger 1.2 or 2.0 if using `swagger-spec-validator`.
Import `validate_spec` from the top-level `swagger_spec_validator` package and use it to validate the specification, passing the version as an argument: ```python from swagger_spec_validator import validate_spec # For Swagger 2.0 validate_spec(your_spec_dict, '2.0') # For Swagger 1.2 validate_spec(your_spec_dict, '1.2') ```
Catch the `SwaggerValidationError` exception and examine its detailed message to identify and correct the specific non-compliance issues within your Swagger specification:
```python
from swagger_spec_validator import validate_spec, SwaggerValidationError
try:
validate_spec(your_spec_dict, '2.0')
print("Specification is valid!")
except SwaggerValidationError as e:
print(f"Specification validation failed: {e}")
# The 'e' object contains details about the validation errors.
```