Debian Codegraph @

docs/usage/openapi/schema_generation.rst

raw
1 Configuring schema generation
2 -----------------------------
3
4 OpenAPI schema generation is enabled by default. To configure it you can pass an instance of
5 :class:`OpenAPIConfig <.openapi.OpenAPIConfig>` to the :class:`Litestar <litestar.app.Litestar>` class using the
6 ``openapi_config`` kwarg:
7
8 .. code-block:: python
9
10 from litestar import Litestar
11 from litestar.openapi import OpenAPIConfig
12
13 app = Litestar(
14 route_handlers=[...], openapi_config=OpenAPIConfig(title="My API", version="1.0.0")
15 )
16
17
18
19 Disabling schema generation
20 +++++++++++++++++++++++++++
21
22 If you wish to disable schema generation and not include the schema endpoints in your API, simply pass ``None`` as the
23 value for ``openapi_config``:
24
25 .. code-block:: python
26
27 from litestar import Litestar
28
29 app = Litestar(route_handlers=[...], openapi_config=None)
30
31
32
33 Configuring schema generation on a route handler
34 -------------------------------------------------
35
36 By default, an `operation <https://spec.openapis.org/oas/latest.html#operation-object>`_ schema is generated for all route
37 handlers. You can omit a route handler from the schema by setting ``include_in_schema=False``:
38
39 .. code-block:: python
40
41 from litestar import get
42
43
44 @get(path="/some-path", include_in_schema=False)
45 def my_route_handler() -> None: ...
46
47 You can also modify the generated schema for the route handler using the following kwargs:
48
49
50 ``tags``
51 A list of strings that correlate to the `tag specification <https://spec.openapis.org/oas/latest.html#tag-object>`_.
52
53 ``security``:
54 A list of dictionaries that correlate to the
55 `security requirements specification <https://spec.openapis.org/oas/latest.html#securityRequirementObject>`_. The
56 values for this key are string keyed dictionaries with the values being a list of objects.
57
58 ``summary``
59 Text used for the route's schema *summary* section.
60
61 ``description``
62 Text used for the route's schema *description* section.
63
64 ``response_description``
65 Text used for the route's response schema *description* section.
66
67 ``operation_class``
68 A subclass of :class:`Operation <.openapi.spec.operation.Operation>` which can be used to fully
69 customize the `operation object <https://spec.openapis.org/oas/v3.1.0#operation-object>`_ for the handler.
70
71 ``operation_id``
72 A string or callable that returns a string, which servers as an identifier used for the route's schema *operationId*.
73
74 ``deprecated``
75 A boolean dictating whether this route should be marked as deprecated in the OpenAPI schema. Defaults
76 to ``False``.
77
78 ``raises``
79 A list of exception classes extending from ``litestar.HttpException``. This list should describe all
80 exceptions raised within the route handler's function/method. The Litestar ``ValidationException`` will be added
81 automatically for the schema if any validation is involved (e.g. there are parameters specified in the
82 method/function). For custom exceptions, a `detail` class property should be defined, which will be integrated
83 into the OpenAPI schema. If `detail` isn't specified and the exception's status code matches one
84 from `stdlib status code <https://docs.python.org/3/library/http.html#http-status-codes>`_, a generic message
85 will be applied.
86
87 ``responses``
88 A dictionary of additional status codes and a description of their expected content.
89 The expected content should be based on a Pydantic model describing its structure. It can also include
90 a description and the expected media type. For example:
91
92 .. note::
93
94 `operation_id` will be prefixed with the method name when function is decorated with `HTTPRouteHandler` and multiple
95 `http_method`. Will also be prefixed with path strings used in `Routers` and `Controllers` to make sure id is unique.
96
97 .. code-block:: python
98
99 from datetime import datetime
100 from typing import Optional
101
102 from pydantic import BaseModel
103
104 from litestar import get
105 from litestar.openapi.datastructures import ResponseSpec
106
107
108 class Item(BaseModel): ...
109
110
111 class ItemNotFound(BaseModel):
112 was_removed: bool
113 removed_at: Optional[datetime]
114
115
116 @get(
117 path="/items/{pk:int}",
118 responses={
119 404: ResponseSpec(
120 data_container=ItemNotFound, description="Item was removed or not found"
121 )
122 },
123 )
124 def retrieve_item(pk: int) -> Item: ...
125
126 You can also specify ``security`` and ``tags`` on higher level of the application, e.g. on a controller, router, or the
127 app instance itself. For example:
128
129 .. code-block:: python
130
131 from litestar import Litestar, get
132 from litestar.openapi import OpenAPIConfig
133 from litestar.openapi.spec import Components, SecurityScheme, Tag
134
135
136 @get(
137 "/public",
138 tags=["public"],
139 security=[{}], # this endpoint is marked as having optional security
140 )
141 def public_path_handler() -> dict[str, str]:
142 return {"hello": "world"}
143
144
145 @get("/other", tags=["internal"], security=[{"apiKey": []}])
146 def internal_path_handler() -> None: ...
147
148
149 app = Litestar(
150 route_handlers=[public_path_handler, internal_path_handler],
151 openapi_config=OpenAPIConfig(
152 title="my api",
153 version="1.0.0",
154 tags=[
155 Tag(name="public", description="This endpoint is for external users"),
156 Tag(name="internal", description="This endpoint is for internal users"),
157 ],
158 security=[{"BearerToken": []}],
159 components=Components(
160 security_schemes={
161 "BearerToken": SecurityScheme(
162 type="http",
163 scheme="bearer",
164 )
165 },
166 ),
167 ),
168 )
169
170
171 Accessing the OpenAPI schema in code
172 ------------------------------------
173
174 The OpenAPI schema is generated during the :class:`Litestar <litestar.app.Litestar>` app's init method. Once init is finished,
175 its accessible as ``app.openapi_schema``. As such you can always access it inside route handlers, dependencies, etc. by
176 access the request instance:
177
178 .. code-block:: python
179
180 from litestar import Request, get
181
182
183 @get(path="/")
184 def my_route_handler(request: Request) -> dict:
185 schema = request.app.openapi_schema
186 return schema.to_schema()
187
188
189 Customizing Pydantic model schemas
190 ----------------------------------
191
192 You can customize the OpenAPI schemas generated for pydantic models by following the guidelines in
193 the `Pydantic docs <https://docs.pydantic.dev/latest/usage/json_schema/>`_.
194
195 Additionally, you can affect how pydantic models are translated into OpenAPI ``components`` by settings a special dunder
196 attribute on the model called ``__schema_name__``:
197
198 .. literalinclude:: /examples/openapi/customize_pydantic_model_name.py
199 :caption: Customize Components Example
200 :language: python
201
202
203 The above will result in an OpenAPI schema object that looks like this:
204
205 .. code-block:: json
206
207 {
208 "openapi": "3.1.0",
209 "info": {"title": "Litestar API", "version": "1.0.0"},
210 "servers": [{"url": "/"}],
211 "paths": {
212 "/id": {
213 "get": {
214 "operationId": "Retrieve Id Handler",
215 "responses": {
216 "200": {
217 "description": "Request fulfilled, document follows",
218 "headers": {},
219 "content": {
220 "application/json": {
221 "schema": {
222 "$ref": "#/components/schemas/IdContainer"
223 }
224 }
225 }
226 }
227 },
228 "deprecated": false
229 }
230 }
231 },
232 "components": {
233 "schemas": {
234 "IdContainer": {
235 "properties": {
236 "id": {"type": "string", "format": "uuid", "title": "Id"}
237 },
238 "type": "object",
239 "required": ["id"],
240 "title": "IdContainer"
241 }
242 }
243 }
244 }
245
246 .. attention::
247
248 If you use multiple pydantic models that use the same name in the schema, you will need to use the `__schema_name__`
249 dunder to ensure each has a unique name in the schema, otherwise the schema components will be ambivalent.
250
251
252
253 Customizing ``Operation`` class
254 -------------------------------
255
256 You can customize the `operation object <https://spec.openapis.org/oas/v3.1.0#operation-object>`_ used for a path in
257 the generated OpenAPI schemas by creating a subclass of :class:`Operation <.openapi.spec.operation.Operation>`.
258
259 This option can be helpful in situations where request data needs to be manually parsed as
260 Litestar will not know how to create the OpenAPI operation data by default.
261
262 .. literalinclude:: /examples/openapi/customize_operation_class.py
263 :caption: Customize Components Example
264 :language: python
265
266
267 The above example will result in an OpenAPI schema object that looks like this:
268
269 .. code-block:: json
270
271 {
272 "info": { "title": "Litestar API", "version": "1.0.0" },
273 "openapi": "3.0.3",
274 "servers": [{ "url": "/" }],
275 "paths": {
276 "/": {
277 "post": {
278 "tags": ["ok"],
279 "summary": "Route",
280 "description": "Requires OK, Returns OK",
281 "operationId": "Route",
282 "requestBody": {
283 "content": {
284 "text": {
285 "schema": { "type": "string", "title": "Body", "example": "OK" }
286 }
287 },
288 "description": "OK is the only accepted value",
289 "required": false
290 },
291 "responses": {
292 "201": {
293 "description": "Document created, URL follows",
294 "headers": {}
295 }
296 },
297 "deprecated": false,
298 "x-codeSamples": [
299 {
300 "lang": "Python",
301 "source": "import requests; requests.get('localhost/example')",
302 "label": "Python"
303 },
304 {
305 "lang": "cURL",
306 "source": "curl -XGET localhost/example",
307 "label": "curl"
308 }
309 ]
310 }
311 }
312 },
313 "components": { "schemas": {} }
314 }
315
316 .. attention::
317
318 OpenAPI Vendor Extension fields need to start with `x-` and should not be processed with the default field name
319 converter. To work around this, Litestar will honor an `alias` field provided to the
320 `dataclass.field <https://docs.python.org/3/library/dataclasses.html#dataclasses.field>`_ metadata
321 when generating the field name in the schema.