This commit is contained in:
Correl Roush 2021-03-22 21:48:55 -04:00
parent 09a737bea3
commit e5a986140a

View file

@ -4,10 +4,11 @@
How to use [[file:20210226114112-openapi_core.org][OpenAPI Core]] How to use [[file:20210226114112-openapi_core.org][OpenAPI Core]]
#+begin_src python :results code :exports both #+begin_src python :results code :exports both
import jsonschema
from openapi_core import create_spec from openapi_core import create_spec
from openapi_core.unmarshalling.schemas.factories import SchemaUnmarshallersFactory from openapi_core.unmarshalling.schemas.factories import SchemaUnmarshallersFactory
spec = create_spec({ spec_dict = {
"openapi": "3.0.0", "openapi": "3.0.0",
"info": { "info": {
"title": "Test API", "title": "Test API",
@ -15,10 +16,18 @@ How to use [[file:20210226114112-openapi_core.org][OpenAPI Core]]
}, },
"components": { "components": {
"schemas": { "schemas": {
"resource_id": {
"type": "string",
"format": "uuid",
},
"resource": { "resource": {
"type": "object", "type": "object",
"properties": {"name": {"type": "string"}}, "properties": {
"required": ["name"], "id": {"$ref": "#/components/schemas/resource_id"},
"name": {"type": "string"},
},
"required": ["id", "name"],
"additionalProperties": False,
}, },
}, },
"securitySchemes": { "securitySchemes": {
@ -53,14 +62,18 @@ How to use [[file:20210226114112-openapi_core.org][OpenAPI Core]]
} }
} }
}, },
}) }
spec = create_spec(spec_dict)
data = { data = {
"id": "bad-id",
"badname": "Name", "badname": "Name",
} }
factory = SchemaUnmarshallersFactory() factory = SchemaUnmarshallersFactory(
unmarshaller = factory.create(spec.components.schemas.get("resource")) resolver=jsonschema.RefResolver(spec.default_url, spec_dict)
)
unmarshaller = factory.create(spec.get_schema("resource"))
try: try:
return unmarshaller(data) return unmarshaller(data)
@ -70,5 +83,5 @@ How to use [[file:20210226114112-openapi_core.org][OpenAPI Core]]
#+RESULTS: #+RESULTS:
#+begin_src python #+begin_src python
Value {'badname': 'Name'} not valid for schema of type SchemaType.OBJECT: (<ValidationError: "'name' is a required property">,) 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)">)
#+end_src #+end_src