OpenAPI Schema Validator

0.8.1 · active · verified Sun Mar 29

openapi-schema-validator is a Python library designed for validating data instances against OpenAPI Schema Specification versions 3.0, 3.1, and 3.2. It leverages `jsonschema` under the hood and provides specific validators for different OpenAPI versions, along with features for handling read/write contexts and managing external references. The library is actively maintained, with version 0.8.1 being the latest, and releases occur as new OpenAPI specifications emerge or features/fixes are required.

Warnings

Install

Imports

Quickstart

The simplest way to validate an instance against an OpenAPI schema is to use the `validate` function. Provide the instance to be validated and the OpenAPI schema object. By default, it expects the latest OpenAPI schema syntax (3.2).

from openapi_schema_validator import validate

# A sample OpenAPI 3.2 schema
schema = {
    "type": "object",
    "required": ["name"],
    "properties": {
        "name": {"type": "string"},
        "age": {
            "type": ["integer", "null"],
            "format": "int32",
            "minimum": 0,
        },
        "birth-date": {"type": "string", "format": "date"},
        "address": {
            "type": "array",
            "prefixItems": [
                {"type": "number"},
                {"type": "string"},
                {"enum": ["Street", "Avenue", "Boulevard"]},
                {"enum": ["NW", "NE", "SW", "SE"]}
            ],
            "items": False,
        }
    },
    "additionalProperties": False,
}

# A valid instance
try:
    validate({"name": "John", "age": 23, "address": [1600, "Pennsylvania", "Avenue"]}, schema)
    print("Instance is valid!")
except Exception as e:
    print(f"Validation failed: {e}")

# An invalid instance (missing required 'name')
try:
    validate({"age": 23}, schema)
except Exception as e:
    print(f"Validation failed as expected: {e}")

# An invalid instance (additional property 'city')
try:
    validate({"name": "John", "city": "London"}, schema)
except Exception as e:
    print(f"Validation failed as expected: {e}")

view raw JSON →