OpenAPI Spec Validator

0.8.4 · active · verified Sun Mar 29

OpenAPI Spec Validator is a Python library that validates OpenAPI 2.0 (aka Swagger), OpenAPI 3.x, and OpenAPI 3.2 specifications. It aims to check for full compliance with the Specification. As of version 0.8.4, it actively supports modern Python versions and features a consistent release cadence, with several minor releases occurring every few months.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to validate an OpenAPI specification using the `validate` function. It includes examples for both invalid and valid in-memory specifications, and comments on how to validate from a file.

from openapi_spec_validator import validate
from openapi_spec_validator.readers import read_from_filename

# Example OpenAPI 3.1.0 specification (invalid, 'info' is missing)
# For a valid spec, ensure 'info' and 'paths' are present.
invalid_spec_data = {
    'openapi': '3.1.0',
    'paths': {},
}

# A minimal valid OpenAPI 3.1.0 specification
valid_spec_data = {
    'openapi': '3.1.0',
    'info': {
        'title': 'Test API',
        'version': '1.0.0'
    },
    'paths': {}
}

print('Attempting to validate invalid_spec_data:')
try:
    validate(invalid_spec_data)
    print('Invalid spec data is VALID (this should not happen)')
except Exception as e:
    print(f'Validation failed as expected: {e}')

print('\nAttempting to validate valid_spec_data:')
try:
    validate(valid_spec_data)
    print('Valid spec data is VALID')
except Exception as e:
    print(f'Validation failed unexpectedly: {e}')

# Example of validating from a file (if 'openapi.yaml' exists)
# You would typically create this file with your OpenAPI definition.
# with open('openapi.yaml', 'w') as f:
#     import yaml
#     yaml.dump(valid_spec_data, f)
#
# try:
#     spec_dict, base_uri = read_from_filename('openapi.yaml')
#     validate(spec_dict, base_uri=base_uri)
#     print('\nValidating from openapi.yaml: SUCCESS')
# except Exception as e:
#     print(f'\nValidating from openapi.yaml: FAILED - {e}')

view raw JSON →