2.7 KiB
2.7 KiB
Validating data against a schema object
How to use OpenAPI Core
import jsonschema
from openapi_core import create_spec
from openapi_core.unmarshalling.schemas.factories import SchemaUnmarshallersFactory
spec_dict = {
"openapi": "3.0.0",
"info": {
"title": "Test API",
"version": "1.0.0",
},
"components": {
"schemas": {
"resource_id": {
"type": "string",
"format": "uuid",
},
"resource": {
"type": "object",
"properties": {
"id": {"$ref": "#/components/schemas/resource_id"},
"name": {"type": "string"},
},
"required": ["id", "name"],
"additionalProperties": False,
},
},
"securitySchemes": {
"basicAuth": {
"type": "http",
"scheme": "bearer",
}
},
},
"security": [{"basicAuth": []}],
"paths": {
"/resource": {
"post": {
"requestBody": {
"required": True,
"content": {
"application/vnd.example.resource+json": {
"schema": {"$ref": "#/components/schemas/resource"},
}
},
},
"responses": {
"200": {
"description": "Success",
"content": {
"application/vnd.example.resource+json": {
"schema": {"$ref": "#/components/schemas/resource"},
}
},
}
},
}
}
},
}
spec = create_spec(spec_dict)
data = {
"id": "bad-id",
"badname": "Name",
}
factory = SchemaUnmarshallersFactory(
resolver=jsonschema.RefResolver(spec.default_url, spec_dict)
)
unmarshaller = factory.create(spec.get_schema("resource"))
try:
return unmarshaller(data)
except Exception as e:
return str(e)
Value {'id': 'bad-id', 'badname': 'Name'} not valid for schema of type SchemaType.OBJECT: (<ValidationError: "'name' is a required property">, <ValidationError: "Additional properties are not allowed ('badname' was unexpected)">)