Swagger Spec Validator

3.0.4 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

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.

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}")

view raw JSON →