Swagger Spec Validator
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.
Warnings
- gotcha This library explicitly supports Swagger 1.2 and Swagger 2.0 specifications only. It does NOT support OpenAPI 3.x. For OpenAPI 3.x validation, consider `openapi-spec-validator` (a separate library).
- gotcha The API is not considered stable and may introduce non-backwards-compatible changes in minor versions.
- gotcha `validate_spec_url` requires network access to fetch the specification. If your specification contains external `$ref` pointers (e.g., to other URLs or local files not bundled with the primary spec), `validate_spec` will also require access to resolve these references.
- gotcha Swagger specifications (and by extension, this validator) rely on a subset of JSON Schema. Some advanced JSON Schema features like `oneOf` or `patternProperties` might not be fully supported or correctly validated.
Install
-
pip install swagger-spec-validator
Imports
- validate_spec_url
from swagger_spec_validator import validate_spec_url
- validate_spec
from swagger_spec_validator import validate_spec
- SwaggerValidationError
from swagger_spec_validator.common import SwaggerValidationError
Quickstart
import yaml
from swagger_spec_validator import validate_spec
from swagger_spec_validator import validate_spec_url
from swagger_spec_validator.common import SwaggerValidationError
# Example 1: Validate a spec from a URL
try:
validate_spec_url('http://petstore.swagger.io/v2/swagger.json')
print("Petstore Swagger 2.0 spec from URL is valid!")
except SwaggerValidationError as e:
print(f"Validation failed for URL spec: {e}")
# Example 2: Validate a spec from a Python dictionary (YAML content)
swagger_spec_content = """
swagger: '2.0'
info:
title: 'My Simple API'
version: '1.0.0'
host: 'api.example.com'
basePath: '/v1'
schemes:
- https
paths:
/users:
get:
summary: 'Get all users'
responses:
'200':
description: 'A list of users'
"""
try:
spec_dict = yaml.safe_load(swagger_spec_content)
validate_spec(spec_dict)
print("Local Swagger 2.0 spec (dictionary) is valid!")
except SwaggerValidationError as e:
print(f"Validation failed for local spec: {e}")
except Exception as e:
print(f"An error occurred: {e}")