File: references.rst

package info (click to toggle)
python-openapi-schema-validator 0.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 372 kB
  • sloc: python: 1,186; makefile: 46
file content (67 lines) | stat: -rw-r--r-- 1,903 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
References
==========

You can resolve JSON Schema references by passing registry

.. code-block:: python

   from openapi_schema_validator import validate
   from referencing import Registry, Resource
   from referencing.jsonschema import DRAFT202012

   # A schema with reference
   schema = {
       "type" : "object",
       "required": [
          "name"
       ],
       "properties": {
           "name": {
               "$ref": "urn:name-schema"
           },
           "age": {
               "$ref": "urn:age-schema"
           },
           "birth-date": {
               "$ref": "urn:birth-date-schema"
           }
       },
       "additionalProperties": False,
   }
   # Referenced schemas
   # In-schema identifier
   name_schema = Resource.from_contents({
       "$schema": "https://json-schema.org/draft/2020-12/schema",
       "type": "string",
   })
   # Explicit identifier
   age_schema = DRAFT202012.create_resource({
       "type": "integer",
       "format": "int32",
       "minimum": 0,
       "maximum": 120,
   })
   # Default identifier
   birth_date_schema = Resource.from_contents({
       "type": "string",
       "format": "date",
   }, default_specification=DRAFT202012)
   registry = Registry().with_resources(
       [
           ("urn:name-schema", name_schema),
           ("urn:age-schema", age_schema),
           ("urn:birth-date-schema", birth_date_schema),
       ],
   )

   # If no exception is raised by validate(), the instance is valid.
   validate({"name": "John", "age": 23}, schema, registry=registry)

   # raises error
   validate({"birth-date": "yesterday", "age": -1}, schema, registry=registry)

   Traceback (most recent call last):
       ...
   ValidationError: 'name' is a required property

For more information about resolving references see `JSON (Schema) Referencing <https://python-jsonschema.readthedocs.io/en/latest/referencing/>`__