Bravado Core

6.1.1 · active · verified Wed Apr 15

bravado-core is a Python library that implements the Swagger 2.0 (OpenAPI Specification v2.0). It provides core functionalities for both client-side and server-side support, including Swagger Schema ingestion and validation, marshalling and unmarshalling of requests and responses, and modeling Swagger definitions as Python classes or dictionaries. The current version is 6.1.1, and it maintains an active, though not rapid, release cadence with new versions typically addressing bugs or minor features rather than frequent major changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a Swagger/OpenAPI specification using `Spec.from_dict`, access defined models as Python types, and validate data against those models. It highlights basic model instantiation and the core validation feature of `bravado-core`.

import json
from bravado_core.spec import Spec
from bravado_core.validate import validate_object

# Example Swagger 2.0 spec (usually loaded from a file or URL)
swagger_dict = {
    "swagger": "2.0",
    "info": {"title": "Test API", "version": "1.0.0"},
    "paths": {},
    "definitions": {
        "Pet": {
            "type": "object",
            "required": ["name"],
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer", "format": "int32", "minimum": 0}
            }
        }
    }
}

# Load the spec
spec = Spec.from_dict(swagger_dict)
print("Swagger spec loaded successfully.")

# Access a defined model
Pet = spec.definitions['Pet']
my_pet = Pet(name='Rex', age=5)
print(f"Created Pet object: Name={my_pet.name}, Age={my_pet.age}")

# Validate an object against a schema
valid_pet_data = {'name': 'Whiskers', 'age': 2}
try:
    validate_object(swagger_spec=spec, json_value=valid_pet_data, swagger_type=spec.definitions['Pet'].swagger_spec)
    print(f"Valid pet data: {valid_pet_data} is valid.")
except Exception as e:
    print(f"Validation failed for valid data: {e}")

invalid_pet_data = {'name': 'Buddy', 'age': -1}
try:
    validate_object(swagger_spec=spec, json_value=invalid_pet_data, swagger_type=spec.definitions['Pet'].swagger_spec)
    print("This line should not be reached for invalid data.")
except Exception as e:
    print(f"Validation error for invalid pet data: {invalid_pet_data} -> {e}")

view raw JSON →