Debian Codegraph @

docs/graphql/data_model_and_resolvers.md

raw
1 # Data model and resolvers
2
3 Almost everything in the [Data model section](../data_model.md) remains valid in GraphQL integration, with a few differences.
4
5 ## GraphQL specific data model
6
7 ### `Enum`
8
9 `Enum` members are represented in the schema using their **name** instead of their value. This is more consistent with the way GraphQL represents enumerations.
10
11 ### `TypedDict`
12
13 `TypedDict` is not supported as an output type. (see [FAQ](#why-typeddict-is-not-supported-as-an-output-type))
14
15 ### `Union`
16 Unions are only supported between **output** object type, which means `dataclass` and `NamedTuple` (and [conversions](../conversions.md)/[dataclass model](../conversions.md#dataclass-model---automatic-conversion-fromto-dataclass)).
17
18 There are 2 exceptions which can be always be used in `Union`:
19
20 - `None`/`Optional`: Types are non-null (marked with an exclamation mark `!` in GraphQL schema) by default; `Optional` types however results in normal GraphQL types (without `!`).
21 - `apischema.UndefinedType`: it is simply ignored. It is useful in resolvers, see [following section](#undefined_param_default)
22
23
24 ## Non-null
25
26 Types are assumed to be non-null by default, as in Python typing. Nullable types are obtained using `typing.Optional` (or `typing.Union` with a `None` argument).
27
28 !!! note
29 There is one exception, when resolver parameter default value is not serializable (and thus cannot be included in the schema), the parameter type is then set as nullable to make the parameter non-required. For example parameters not `Optional` but with `Undefined` default value will be marked as nullable. This is only for the schema, the default value is still used at execution.
30
31 ## Undefined
32
33 In output, `Undefined` is converted to `None`; so in the schema, `Union[T, UndefinedType]` will be nullable.
34
35 In input, fields become nullable when `Undefined` is their default value.
36
37 ## Interfaces
38
39 Interfaces are simply classes marked with `apischema.graphql.interface` decorator. An object type implements an interface when its class inherits from an interface-marked class, or when it has [flattened fields](../data_model.md#composition-over-inheritance---composed-dataclasses-flattening) of interface-marked dataclass.
40
41 ```python
42 {!interface.py!}
43 ```
44
45 ## Resolvers
46
47 All `dataclass`/`NamedTuple` fields (excepted [skipped](../data_model.md#skip-dataclass-field)) are resolved with their [alias](../json_schema.md#field-alias) in the GraphQL schema.
48
49 Custom resolvers can also be added by marking methods with `apischema.graphql.resolver` decorator — resolvers share a common interface with [`apischema.serialized`](../de_serialization.md#serialized-methodsproperties), with a few differences.
50
51 Methods can be synchronous or asynchronous (defined with `async def` or annotated with an `typing.Awaitable` return type).
52
53 Resolvers parameters are included in the schema with their type, and their default value.
54
55 ```python
56 {!resolver.py!}
57 ```
58
59 ### `GraphQLResolveInfo` parameter
60
61 Resolvers can have an additional parameter of type [`graphql.GraphQLResolveInfo`](https://graphql-core-3.readthedocs.io/en/latest/modules/type.html?highlight=GraphQLResolveInfo#graphql.type.GraphQLResolveInfo) (or `Optional[graphql.GraphQLResolveInfo]`), which is automatically injected when the resolver is executed in the context of a GraphQL request. This parameter contains the info about the current GraphQL request being executed.
62
63 ### Undefined parameter default — `null` vs. `undefined`
64
65 `Undefined` can be used as default value of resolver parameters. It can be to distinguish a `null` input from an absent/`undefined` input. In fact, `null` value will result in a `None` argument where no value will use the default value, `Undefined` so.
66
67 ```python
68 {!undefined_default.py!}
69 ```
70
71 ### Error handling
72
73 Errors occurring in resolvers can be caught in a dedicated error handler registered with `error_handler` parameter. This function takes in parameters the exception, the object, the [info](#graphqlresolveinfo-parameter) and the *kwargs* of the failing resolver; it can return a new value or raise the current or another exception — it can for example be used to log errors without throwing the complete serialization.
74
75 The resulting serialization type will be a `Union` of the normal type and the error handling type; if the error handler always raises, use [`typing.NoReturn`](https://docs.python.org/3/library/typing.html#typing.NoReturn) annotation.
76
77 `error_handler=None` correspond to a default handler which only return `None` — exception is thus discarded and the resolver type becomes `Optional`.
78
79 The error handler is only executed by *apischema* serialization process, it's not added to the function, so this one can be executed normally and raise an exception in the rest of your code.
80
81 Error handler can be synchronous or asynchronous.
82
83 ```python
84 {!resolver_error.py!}
85 ```
86
87 ### Parameters metadata
88
89 Resolvers parameters can have metadata like dataclass fields. They can be passed using `typing.Annotated`.
90
91 ```python
92 {!resolver_metadata.py!}
93 ```
94
95 !!! note
96 Metadata can also be passed with `parameters_metadata` parameter; it takes a mapping of parameter names as key and mapped metadata as value.
97
98 ### Parameters base schema
99
100 Following the example of [type/field/method base schema](../json_schema.md#base-schema), resolver parameters also support a base schema definition
101
102 ```python
103 {!base_schema_parameter.py!}
104 ```
105
106 ## Scalars
107
108 `NewType` or non-object types annotated with `type_name` will be translated in the GraphQL schema by a `scalar`. By the way, `Any` will automatically be translated to a `JSON` scalar, as it is deserialized from and serialized to JSON.
109
110 ```python
111 {!scalar.py!}
112 ```
113
114 ## ID type
115 GraphQL `ID` has no precise specification and is defined according API needs; it can be a UUID or/and ObjectId, etc.
116
117 `apischema.graphql_schema` has a parameter `id_types` which can be used to define which types will be marked as `ID` in the generated schema. Parameter value can be either a collection of types (each type will then be mapped to `ID` scalar), or a predicate returning if the given type must be marked as `ID`.
118
119 ```python
120 {!id_type.py!}
121 ```
122
123 !!! note
124 `ID` type could also be identified using `typing.Annotated` and a predicate looking into annotations.
125
126 *apischema* also provides a simple `ID` type with `apischema.graphql.ID`. It is just defined as a `NewType` of string, so you can use it when you want to manipulate raw `ID` strings in your resolvers.
127
128
129 ### ID encoding
130
131 `ID` encoding can directly be controlled the `id_encoding` parameters of `graphql_schema`. A current practice is to use *base64* encoding for `ID`.
132
133 ```python
134 {!id_conversion.py!}
135 ```
136
137 !!! note
138 You can also use `relay.base64_encoding` (see [next section](relay.md#id-encoding))
139
140 !!! note
141 `ID` serialization (respectively deserialization) is applied **after** *apischema* conversions (respectively before *apischema* conversion): in the example, uuid is already converted into string before being passed to `id_serializer`.
142
143 If you use base64 encodeing and an ID type which is converted by *apischema* to a base64 str, you will get a double encoded base64 string
144
145
146 ## Tagged unions
147
148 !!! important
149 This feature has a provisional status, as the concerned [GraphQL RFC](https://github.com/graphql/graphql-spec/pull/733) is not finalized.
150
151 *apischema* provides a `apischema.tagged_unions.TaggedUnion` base class which helps to implement the *tagged union* pattern.
152 It's fields **must** be typed using `apischema.tagged_unions.Tagged` generic type.
153
154 ```python
155 {!tagged_union.py!}
156 ```
157
158 ### JSON schema
159
160 Tagged unions JSON schema uses `minProperties: 1` and `maxProperties: 1`.
161
162 ```python
163 {!tagged_union_json_schema.py!}
164 ```
165
166 ### GraphQL schema
167
168 As tagged unions are not (yet?) part of the GraphQL spec, they are just implemented as normal (input) object type with nullable fields. An error is raised if several tags are passed in input.
169
170 ```python
171 {!tagged_union_graphql_schema.py!}
172 ```
173
174 ## FAQ
175
176 #### Why `TypedDict` is not supported as an output type?
177
178 At first, `TypedDict` subclasses are not real classes, so they cannot be used to check types at runtime. Runtime check is however requried to disambiguate unions/interfaces. A hack could be done to solve this issue, but there is another one which cannot be hacked: `TypedDict` inheritance hierarchy is lost at runtime, so they don't play nicely with the interface concept.