| 1 |
# JSON schema |
| 2 |
|
| 3 |
## JSON schema generation |
| 4 |
|
| 5 |
JSON schema can be generated from data model. However, because of all possible [customizations](conversions.md), the schema can differ between deserilialization and serialization. In common cases, `deserialization_schema` and `serialization_schema` will give the same result. |
| 6 |
|
| 7 |
```python |
| 8 |
{!json_schema.py!} |
| 9 |
``` |
| 10 |
|
| 11 |
## Field alias |
| 12 |
|
| 13 |
Sometimes dataclass field names can clash with a language keyword, sometimes the property name is not convenient. Hopefully, field can define an `alias` which will be used in schema and deserialization/serialization. |
| 14 |
|
| 15 |
```python |
| 16 |
{!alias.py!} |
| 17 |
``` |
| 18 |
|
| 19 |
### Alias all fields |
| 20 |
|
| 21 |
Field aliasing can also be done at class level by specifying an aliasing function. This aliaser is applied to field alias if defined or field name, or not applied if `override=False` is specified. |
| 22 |
|
| 23 |
```python |
| 24 |
{!aliaser.py!} |
| 25 |
``` |
| 26 |
|
| 27 |
Class-level aliasing can be used to define a *camelCase* API. |
| 28 |
|
| 29 |
### Dynamic aliasing and default aliaser |
| 30 |
|
| 31 |
*apischema* operations `deserialize`/`serialize`/`deserialization_schema`/`serialization_schema` provide an `aliaser` parameter which will be applied on every fields being processed in this operation. |
| 32 |
|
| 33 |
Similar to [`strictness configuration`](de_serialization.md#strictness-configuration), this parameter has a default value controlled by `apischema.settings.aliaser`. |
| 34 |
|
| 35 |
It can be used for example to make all an application use *camelCase*. Actually, there is a shortcut for that: |
| 36 |
|
| 37 |
Otherwise, it's used the same way than [`settings.coercer`](de_serialization.md#strictness-configuration). |
| 38 |
|
| 39 |
```python |
| 40 |
from apischema import settings |
| 41 |
|
| 42 |
settings.camel_case = True |
| 43 |
``` |
| 44 |
|
| 45 |
!!! note |
| 46 |
Dynamic aliaser ignores `override=False` |
| 47 |
|
| 48 |
## Schema annotations |
| 49 |
|
| 50 |
Type annotations are not enough to express a complete schema, but *apischema* has a function for that; `schema` can be used both as type decorator or field metadata. |
| 51 |
|
| 52 |
```python |
| 53 |
{!schema.py!} |
| 54 |
``` |
| 55 |
|
| 56 |
!!! note |
| 57 |
Schema are particularly useful with `NewType`. For example, if you use prefixed ids, you can use a `NewType` with a `pattern` schema to validate them, and benefit of more precise type checking. |
| 58 |
|
| 59 |
The following keys are available (they are sometimes shorten compared to JSON schema original for code concision and snake_case): |
| 60 |
|
| 61 |
Key | JSON schema keyword | type restriction |
| 62 |
--- | --- | --- |
| 63 |
title | / | / |
| 64 |
description | / | / |
| 65 |
default | / | / |
| 66 |
examples | / | / |
| 67 |
min | minimum | `int` |
| 68 |
max | maximum | `int` |
| 69 |
exc_min | exclusiveMinimum | `int` |
| 70 |
exc_max | exclusiveMaximum | `int` |
| 71 |
mult_of | multipleOf | `int` |
| 72 |
format | / | `str` |
| 73 |
media_type | contentMediaType | `str` |
| 74 |
encoding | contentEncoding | `str` |
| 75 |
min_len | minLength | `str` |
| 76 |
max_len | maxLength | `str` |
| 77 |
pattern | / | `str` |
| 78 |
min_items | minItems | `list` |
| 79 |
max_items | maxItems | `list` |
| 80 |
unique | / | `list` |
| 81 |
min_props | minProperties | `dict` |
| 82 |
max_props | maxProperties | `dict` |
| 83 |
|
| 84 |
!!! note |
| 85 |
In case of field schema, field default value will be serialized (if possible) to add `default` keyword to the schema. |
| 86 |
|
| 87 |
### Constraints validation |
| 88 |
|
| 89 |
JSON schema constrains the data deserialized; these constraints are naturally used for validation. |
| 90 |
|
| 91 |
```python |
| 92 |
{!validation_error.py!} |
| 93 |
``` |
| 94 |
|
| 95 |
!!! note |
| 96 |
Error message are fully [customizable](validation.md#constraint-errors-customization) |
| 97 |
|
| 98 |
### Extra schema |
| 99 |
|
| 100 |
`schema` has two other arguments: `extra` and `override`, which give a finer control of the JSON schema generated: `extra` and `override`. It can be used for example to build "strict" unions (using `oneOf` instead of `anyOf`) |
| 101 |
|
| 102 |
```python |
| 103 |
{!strict_union.py!} |
| 104 |
``` |
| 105 |
|
| 106 |
### Base `schema` |
| 107 |
|
| 108 |
`apischema.settings.base_schema` can be used to define "base schema" for the different kind of objects: types, object fields or (serialized) methods. |
| 109 |
|
| 110 |
```python |
| 111 |
{!base_schema.py!} |
| 112 |
``` |
| 113 |
|
| 114 |
Base schema will be merged with `schema` defined at type/field/method level. |
| 115 |
|
| 116 |
## Required field with default value |
| 117 |
|
| 118 |
By default, a dataclass/namedtuple field will be tagged `required` if it doesn't have a default value. |
| 119 |
|
| 120 |
However, you may want to have a default value for a field in order to be more convenient in your code, but still make the field required. One could think about some schema model where version is fixed but is required, for example JSON-RPC with `"jsonrpc": "2.0"`. That's done with field metadata `required`. |
| 121 |
|
| 122 |
```python |
| 123 |
{!required.py!} |
| 124 |
``` |
| 125 |
|
| 126 |
## Additional properties / pattern properties |
| 127 |
|
| 128 |
### With `Mapping` |
| 129 |
Schema of a `Mapping`/`dict` type is naturally translated to `"additionalProperties": <schema of the value type>`. |
| 130 |
|
| 131 |
However when the schema of the key has a `pattern`, it will give a `"patternProperties": {<key pattern>: <schema of the value type>}` |
| 132 |
|
| 133 |
### With dataclass |
| 134 |
|
| 135 |
`additionalProperties`/`patternProperties` can be added to dataclasses by using fields annotated with `properties` metadata. Properties not mapped on regular fields will be deserialized into this fields; they must have a `Mapping` type, or be [deserializable](conversions.md) from a `Mapping`, because they are instantiated with a mapping. |
| 136 |
|
| 137 |
```python |
| 138 |
{!properties.py!} |
| 139 |
``` |
| 140 |
|
| 141 |
!!! note |
| 142 |
Of course, a dataclass can only have a single `properties` field without pattern, because it makes no sens to have several `additionalProperties`. |
| 143 |
|
| 144 |
## Property dependencies |
| 145 |
|
| 146 |
*apischema* supports [property dependencies](https://json-schema.org/understanding-json-schema/reference/conditionals.html#dependentrequired) for dataclass through a class member. Dependencies are also used in validation. |
| 147 |
|
| 148 |
```python |
| 149 |
{!dependent_required.py!} |
| 150 |
``` |
| 151 |
|
| 152 |
Because bidirectional dependencies are a common idiom, *apischema* provides a shortcut notation; it's indeed possible to write `dependent_required([credit_card, billing_adress])`. |
| 153 |
|
| 154 |
## JSON schema reference |
| 155 |
|
| 156 |
For complex schema with type reuse, it's convenient to extract definitions of schema components in order to reuse them — it's even mandatory for recursive types; JSON schema use JSON pointers "$ref" to refer to the definitions. *apischema* handles this feature natively. |
| 157 |
|
| 158 |
```python |
| 159 |
{!complex_schema.py!} |
| 160 |
``` |
| 161 |
|
| 162 |
### Use reference only for reused types |
| 163 |
|
| 164 |
*apischema* can control the reference use through the boolean `all_ref` parameter of `deserialization_schema`/`serialization_schema`: |
| 165 |
|
| 166 |
- `all_refs=True` -> all types with a reference will be put in the definitions and referenced with `$ref`; |
| 167 |
- `all_refs=False` -> only types which are reused in the schema are put in definitions |
| 168 |
|
| 169 |
`all_refs` default value depends on the [JSON schema version](#json-schemaopenapi-version): it's `False` for JSON schema drafts but `True` for OpenAPI. |
| 170 |
|
| 171 |
```python |
| 172 |
{!all_refs.py!} |
| 173 |
``` |
| 174 |
|
| 175 |
### Set reference name |
| 176 |
|
| 177 |
In the previous examples, types were referenced using their name. This is indeed the default behavior for every classes/`NewType`s (except primitive `int`/`str`/`bool`/`float`). |
| 178 |
|
| 179 |
It's possible to override the default reference name using `apischema.type_name`; passing `None` instead of a string will remove the reference, making the type unable to be referenced as a separate definition in the schema. |
| 180 |
|
| 181 |
```python |
| 182 |
{!type_name.py!} |
| 183 |
``` |
| 184 |
|
| 185 |
!!! note |
| 186 |
Builtin collections are interchangeable when a type_name is registered. For example, if a name is registered for `list[Foo]`, this name will also be used for `Sequence[Foo]` or `Collection[Foo]`. |
| 187 |
|
| 188 |
Generic aliases can have a type name, but they need to be specialized; `Foo[T, int]` cannot have a type name but `Foo[str, int]` can. However, generic classes can get a dynamic type name depending on their generic argument, passing a name factory to `type_name`: |
| 189 |
|
| 190 |
```python |
| 191 |
{!generic_type_name.py!} |
| 192 |
``` |
| 193 |
|
| 194 |
The default behavior can also be customized using `apischema.settings.default_type_name`: |
| 195 |
|
| 196 |
|
| 197 |
### Reference factory |
| 198 |
|
| 199 |
In JSON schema, `$ref` looks like `#/$defs/Foo`, not just `Foo`. In fact, schema generation use the ref given by `type_name`/`default_type_name` and pass it to a `ref_factory` function (a parameter of schema generation functions) which will convert it to its final form. [JSON schema version](#json-schemaopenapi-version) comes with its default `ref_factory`, for draft 2020-12, it prefixes the ref with `#/$defs/`, while it prefixes with `#/components/schema` in case of OpenAPI. |
| 200 |
|
| 201 |
```python |
| 202 |
{!ref_factory.py!} |
| 203 |
``` |
| 204 |
|
| 205 |
!!! note |
| 206 |
When `ref_factory` is passed in arguments, definitions are not added to the generated schema. That's because `ref_factory` would surely change definitions location, so there would be no interest to add them with a wrong location. These definitions can of course be generated separately with `definitions_schema`. |
| 207 |
|
| 208 |
|
| 209 |
### Definitions schema |
| 210 |
|
| 211 |
Definitions schemas can also be extracted using `apischema.json_schema.definitions_schema`. It takes two lists `deserialization`/`serialization` of types (or tuple of type + [dynamic conversion](conversions.md)) and returns a dictionary of all referenced schemas. |
| 212 |
|
| 213 |
!!! note |
| 214 |
This is especially useful when it comes to OpenAPI schema to generate the components section. |
| 215 |
|
| 216 |
```python |
| 217 |
{!definitions_schema.py!} |
| 218 |
``` |
| 219 |
|
| 220 |
## JSON schema / OpenAPI version |
| 221 |
|
| 222 |
JSON schema has several versions — OpenAPI is treated as a JSON schema version. If *apischema* natively use the last one: draft 2020-12, it is possible to specify a schema version which will be used for the generation. |
| 223 |
|
| 224 |
```python |
| 225 |
{!schema_versions.py!} |
| 226 |
``` |
| 227 |
|
| 228 |
## OpenAPI Discriminator |
| 229 |
|
| 230 |
OpenAPI defines a [discriminator object](https://spec.openapis.org/oas/v3.1.0#discriminator-object) which can be used to shortcut deserialization of union of object types. |
| 231 |
|
| 232 |
*apischema* provides two different ways to declare a discriminator: |
| 233 |
|
| 234 |
- as an `Annotated` metadata of a union ; |
| 235 |
```python |
| 236 |
{!union_discriminator.py!} |
| 237 |
``` |
| 238 |
|
| 239 |
- as a decorator of base class. |
| 240 |
```python |
| 241 |
{!inherited_discriminator.py!} |
| 242 |
``` |
| 243 |
|
| 244 |
!!! note |
| 245 |
Using discriminator doesn't require to have a dedicated field (except for `TypedDict`) |
| 246 |
|
| 247 |
Performance of union deserialization can be [improved](optimizations_and_benchmark.md#discriminator) using discriminator. |
| 248 |
|
| 249 |
|
| 250 |
## `readOnly` / `writeOnly` |
| 251 |
Dataclasses `InitVar` and `field(init=False)` fields will be flagged respectively with `"writeOnly": true` and `"readOnly": true` in the generated schema. |
| 252 |
|
| 253 |
In [definitions schema](#definitions-schema), if a type appears both in deserialization and serialization, properties are merged and the resulting schema contains then `readOnly` and `writeOnly` properties. By the way, the `required` is not merged because it can't (it would mess up validation if some not-init field was required), so deserialization `required` is kept because it's more important as it can be used in validation (OpenAPI 3.0 semantic which allows the merge [has been dropped](https://www.openapis.org/blog/2020/06/18/openapi-3-1-0-rc0-its-here) in 3.1, so it has not been judged useful to be supported) |