fastapi 0.128.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. fastapi/__init__.py +25 -0
  2. fastapi/__main__.py +3 -0
  3. fastapi/_compat/__init__.py +41 -0
  4. fastapi/_compat/shared.py +206 -0
  5. fastapi/_compat/v2.py +568 -0
  6. fastapi/applications.py +4669 -0
  7. fastapi/background.py +60 -0
  8. fastapi/cli.py +13 -0
  9. fastapi/concurrency.py +41 -0
  10. fastapi/datastructures.py +183 -0
  11. fastapi/dependencies/__init__.py +0 -0
  12. fastapi/dependencies/models.py +193 -0
  13. fastapi/dependencies/utils.py +1021 -0
  14. fastapi/encoders.py +346 -0
  15. fastapi/exception_handlers.py +34 -0
  16. fastapi/exceptions.py +246 -0
  17. fastapi/logger.py +3 -0
  18. fastapi/middleware/__init__.py +1 -0
  19. fastapi/middleware/asyncexitstack.py +18 -0
  20. fastapi/middleware/cors.py +1 -0
  21. fastapi/middleware/gzip.py +1 -0
  22. fastapi/middleware/httpsredirect.py +3 -0
  23. fastapi/middleware/trustedhost.py +3 -0
  24. fastapi/middleware/wsgi.py +1 -0
  25. fastapi/openapi/__init__.py +0 -0
  26. fastapi/openapi/constants.py +3 -0
  27. fastapi/openapi/docs.py +344 -0
  28. fastapi/openapi/models.py +438 -0
  29. fastapi/openapi/utils.py +567 -0
  30. fastapi/param_functions.py +2369 -0
  31. fastapi/params.py +755 -0
  32. fastapi/py.typed +0 -0
  33. fastapi/requests.py +2 -0
  34. fastapi/responses.py +48 -0
  35. fastapi/routing.py +4508 -0
  36. fastapi/security/__init__.py +15 -0
  37. fastapi/security/api_key.py +318 -0
  38. fastapi/security/base.py +6 -0
  39. fastapi/security/http.py +423 -0
  40. fastapi/security/oauth2.py +663 -0
  41. fastapi/security/open_id_connect_url.py +94 -0
  42. fastapi/security/utils.py +10 -0
  43. fastapi/staticfiles.py +1 -0
  44. fastapi/templating.py +1 -0
  45. fastapi/testclient.py +1 -0
  46. fastapi/types.py +11 -0
  47. fastapi/utils.py +164 -0
  48. fastapi/websockets.py +3 -0
  49. fastapi-0.128.0.dist-info/METADATA +645 -0
  50. fastapi-0.128.0.dist-info/RECORD +53 -0
  51. fastapi-0.128.0.dist-info/WHEEL +4 -0
  52. fastapi-0.128.0.dist-info/entry_points.txt +5 -0
  53. fastapi-0.128.0.dist-info/licenses/LICENSE +21 -0
fastapi/routing.py ADDED
@@ -0,0 +1,4508 @@
1
+ import email.message
2
+ import functools
3
+ import inspect
4
+ import json
5
+ from collections.abc import (
6
+ AsyncIterator,
7
+ Awaitable,
8
+ Collection,
9
+ Coroutine,
10
+ Mapping,
11
+ Sequence,
12
+ )
13
+ from contextlib import AsyncExitStack, asynccontextmanager
14
+ from enum import Enum, IntEnum
15
+ from typing import (
16
+ Annotated,
17
+ Any,
18
+ Callable,
19
+ Optional,
20
+ Union,
21
+ )
22
+
23
+ from annotated_doc import Doc
24
+ from fastapi import params
25
+ from fastapi._compat import (
26
+ ModelField,
27
+ Undefined,
28
+ annotation_is_pydantic_v1,
29
+ lenient_issubclass,
30
+ )
31
+ from fastapi.datastructures import Default, DefaultPlaceholder
32
+ from fastapi.dependencies.models import Dependant
33
+ from fastapi.dependencies.utils import (
34
+ _should_embed_body_fields,
35
+ get_body_field,
36
+ get_dependant,
37
+ get_flat_dependant,
38
+ get_parameterless_sub_dependant,
39
+ get_typed_return_annotation,
40
+ solve_dependencies,
41
+ )
42
+ from fastapi.encoders import jsonable_encoder
43
+ from fastapi.exceptions import (
44
+ EndpointContext,
45
+ FastAPIError,
46
+ PydanticV1NotSupportedError,
47
+ RequestValidationError,
48
+ ResponseValidationError,
49
+ WebSocketRequestValidationError,
50
+ )
51
+ from fastapi.types import DecoratedCallable, IncEx
52
+ from fastapi.utils import (
53
+ create_cloned_field,
54
+ create_model_field,
55
+ generate_unique_id,
56
+ get_value_or_default,
57
+ is_body_allowed_for_status_code,
58
+ )
59
+ from starlette import routing
60
+ from starlette._exception_handler import wrap_app_handling_exceptions
61
+ from starlette._utils import is_async_callable
62
+ from starlette.concurrency import run_in_threadpool
63
+ from starlette.exceptions import HTTPException
64
+ from starlette.requests import Request
65
+ from starlette.responses import JSONResponse, Response
66
+ from starlette.routing import (
67
+ BaseRoute,
68
+ Match,
69
+ compile_path,
70
+ get_name,
71
+ )
72
+ from starlette.routing import Mount as Mount # noqa
73
+ from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send
74
+ from starlette.websockets import WebSocket
75
+ from typing_extensions import deprecated
76
+
77
+
78
+ # Copy of starlette.routing.request_response modified to include the
79
+ # dependencies' AsyncExitStack
80
+ def request_response(
81
+ func: Callable[[Request], Union[Awaitable[Response], Response]],
82
+ ) -> ASGIApp:
83
+ """
84
+ Takes a function or coroutine `func(request) -> response`,
85
+ and returns an ASGI application.
86
+ """
87
+ f: Callable[[Request], Awaitable[Response]] = (
88
+ func if is_async_callable(func) else functools.partial(run_in_threadpool, func) # type:ignore
89
+ )
90
+
91
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
92
+ request = Request(scope, receive, send)
93
+
94
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
95
+ # Starts customization
96
+ response_awaited = False
97
+ async with AsyncExitStack() as request_stack:
98
+ scope["fastapi_inner_astack"] = request_stack
99
+ async with AsyncExitStack() as function_stack:
100
+ scope["fastapi_function_astack"] = function_stack
101
+ response = await f(request)
102
+ await response(scope, receive, send)
103
+ # Continues customization
104
+ response_awaited = True
105
+ if not response_awaited:
106
+ raise FastAPIError(
107
+ "Response not awaited. There's a high chance that the "
108
+ "application code is raising an exception and a dependency with yield "
109
+ "has a block with a bare except, or a block with except Exception, "
110
+ "and is not raising the exception again. Read more about it in the "
111
+ "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except"
112
+ )
113
+
114
+ # Same as in Starlette
115
+ await wrap_app_handling_exceptions(app, request)(scope, receive, send)
116
+
117
+ return app
118
+
119
+
120
+ # Copy of starlette.routing.websocket_session modified to include the
121
+ # dependencies' AsyncExitStack
122
+ def websocket_session(
123
+ func: Callable[[WebSocket], Awaitable[None]],
124
+ ) -> ASGIApp:
125
+ """
126
+ Takes a coroutine `func(session)`, and returns an ASGI application.
127
+ """
128
+ # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async"
129
+
130
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
131
+ session = WebSocket(scope, receive=receive, send=send)
132
+
133
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
134
+ async with AsyncExitStack() as request_stack:
135
+ scope["fastapi_inner_astack"] = request_stack
136
+ async with AsyncExitStack() as function_stack:
137
+ scope["fastapi_function_astack"] = function_stack
138
+ await func(session)
139
+
140
+ # Same as in Starlette
141
+ await wrap_app_handling_exceptions(app, session)(scope, receive, send)
142
+
143
+ return app
144
+
145
+
146
+ def _merge_lifespan_context(
147
+ original_context: Lifespan[Any], nested_context: Lifespan[Any]
148
+ ) -> Lifespan[Any]:
149
+ @asynccontextmanager
150
+ async def merged_lifespan(
151
+ app: AppType,
152
+ ) -> AsyncIterator[Optional[Mapping[str, Any]]]:
153
+ async with original_context(app) as maybe_original_state:
154
+ async with nested_context(app) as maybe_nested_state:
155
+ if maybe_nested_state is None and maybe_original_state is None:
156
+ yield None # old ASGI compatibility
157
+ else:
158
+ yield {**(maybe_nested_state or {}), **(maybe_original_state or {})}
159
+
160
+ return merged_lifespan # type: ignore[return-value]
161
+
162
+
163
+ # Cache for endpoint context to avoid re-extracting on every request
164
+ _endpoint_context_cache: dict[int, EndpointContext] = {}
165
+
166
+
167
+ def _extract_endpoint_context(func: Any) -> EndpointContext:
168
+ """Extract endpoint context with caching to avoid repeated file I/O."""
169
+ func_id = id(func)
170
+
171
+ if func_id in _endpoint_context_cache:
172
+ return _endpoint_context_cache[func_id]
173
+
174
+ try:
175
+ ctx: EndpointContext = {}
176
+
177
+ if (source_file := inspect.getsourcefile(func)) is not None:
178
+ ctx["file"] = source_file
179
+ if (line_number := inspect.getsourcelines(func)[1]) is not None:
180
+ ctx["line"] = line_number
181
+ if (func_name := getattr(func, "__name__", None)) is not None:
182
+ ctx["function"] = func_name
183
+ except Exception:
184
+ ctx = EndpointContext()
185
+
186
+ _endpoint_context_cache[func_id] = ctx
187
+ return ctx
188
+
189
+
190
+ async def serialize_response(
191
+ *,
192
+ field: Optional[ModelField] = None,
193
+ response_content: Any,
194
+ include: Optional[IncEx] = None,
195
+ exclude: Optional[IncEx] = None,
196
+ by_alias: bool = True,
197
+ exclude_unset: bool = False,
198
+ exclude_defaults: bool = False,
199
+ exclude_none: bool = False,
200
+ is_coroutine: bool = True,
201
+ endpoint_ctx: Optional[EndpointContext] = None,
202
+ ) -> Any:
203
+ if field:
204
+ errors = []
205
+ if is_coroutine:
206
+ value, errors_ = field.validate(response_content, {}, loc=("response",))
207
+ else:
208
+ value, errors_ = await run_in_threadpool(
209
+ field.validate, response_content, {}, loc=("response",)
210
+ )
211
+ if isinstance(errors_, list):
212
+ errors.extend(errors_)
213
+ if errors:
214
+ ctx = endpoint_ctx or EndpointContext()
215
+ raise ResponseValidationError(
216
+ errors=errors,
217
+ body=response_content,
218
+ endpoint_ctx=ctx,
219
+ )
220
+
221
+ return field.serialize(
222
+ value,
223
+ include=include,
224
+ exclude=exclude,
225
+ by_alias=by_alias,
226
+ exclude_unset=exclude_unset,
227
+ exclude_defaults=exclude_defaults,
228
+ exclude_none=exclude_none,
229
+ )
230
+
231
+ else:
232
+ return jsonable_encoder(response_content)
233
+
234
+
235
+ async def run_endpoint_function(
236
+ *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool
237
+ ) -> Any:
238
+ # Only called by get_request_handler. Has been split into its own function to
239
+ # facilitate profiling endpoints, since inner functions are harder to profile.
240
+ assert dependant.call is not None, "dependant.call must be a function"
241
+
242
+ if is_coroutine:
243
+ return await dependant.call(**values)
244
+ else:
245
+ return await run_in_threadpool(dependant.call, **values)
246
+
247
+
248
+ def get_request_handler(
249
+ dependant: Dependant,
250
+ body_field: Optional[ModelField] = None,
251
+ status_code: Optional[int] = None,
252
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(JSONResponse),
253
+ response_field: Optional[ModelField] = None,
254
+ response_model_include: Optional[IncEx] = None,
255
+ response_model_exclude: Optional[IncEx] = None,
256
+ response_model_by_alias: bool = True,
257
+ response_model_exclude_unset: bool = False,
258
+ response_model_exclude_defaults: bool = False,
259
+ response_model_exclude_none: bool = False,
260
+ dependency_overrides_provider: Optional[Any] = None,
261
+ embed_body_fields: bool = False,
262
+ ) -> Callable[[Request], Coroutine[Any, Any, Response]]:
263
+ assert dependant.call is not None, "dependant.call must be a function"
264
+ is_coroutine = dependant.is_coroutine_callable
265
+ is_body_form = body_field and isinstance(body_field.field_info, params.Form)
266
+ if isinstance(response_class, DefaultPlaceholder):
267
+ actual_response_class: type[Response] = response_class.value
268
+ else:
269
+ actual_response_class = response_class
270
+
271
+ async def app(request: Request) -> Response:
272
+ response: Union[Response, None] = None
273
+ file_stack = request.scope.get("fastapi_middleware_astack")
274
+ assert isinstance(file_stack, AsyncExitStack), (
275
+ "fastapi_middleware_astack not found in request scope"
276
+ )
277
+
278
+ # Extract endpoint context for error messages
279
+ endpoint_ctx = (
280
+ _extract_endpoint_context(dependant.call)
281
+ if dependant.call
282
+ else EndpointContext()
283
+ )
284
+
285
+ if dependant.path:
286
+ # For mounted sub-apps, include the mount path prefix
287
+ mount_path = request.scope.get("root_path", "").rstrip("/")
288
+ endpoint_ctx["path"] = f"{request.method} {mount_path}{dependant.path}"
289
+
290
+ # Read body and auto-close files
291
+ try:
292
+ body: Any = None
293
+ if body_field:
294
+ if is_body_form:
295
+ body = await request.form()
296
+ file_stack.push_async_callback(body.close)
297
+ else:
298
+ body_bytes = await request.body()
299
+ if body_bytes:
300
+ json_body: Any = Undefined
301
+ content_type_value = request.headers.get("content-type")
302
+ if not content_type_value:
303
+ json_body = await request.json()
304
+ else:
305
+ message = email.message.Message()
306
+ message["content-type"] = content_type_value
307
+ if message.get_content_maintype() == "application":
308
+ subtype = message.get_content_subtype()
309
+ if subtype == "json" or subtype.endswith("+json"):
310
+ json_body = await request.json()
311
+ if json_body != Undefined:
312
+ body = json_body
313
+ else:
314
+ body = body_bytes
315
+ except json.JSONDecodeError as e:
316
+ validation_error = RequestValidationError(
317
+ [
318
+ {
319
+ "type": "json_invalid",
320
+ "loc": ("body", e.pos),
321
+ "msg": "JSON decode error",
322
+ "input": {},
323
+ "ctx": {"error": e.msg},
324
+ }
325
+ ],
326
+ body=e.doc,
327
+ endpoint_ctx=endpoint_ctx,
328
+ )
329
+ raise validation_error from e
330
+ except HTTPException:
331
+ # If a middleware raises an HTTPException, it should be raised again
332
+ raise
333
+ except Exception as e:
334
+ http_error = HTTPException(
335
+ status_code=400, detail="There was an error parsing the body"
336
+ )
337
+ raise http_error from e
338
+
339
+ # Solve dependencies and run path operation function, auto-closing dependencies
340
+ errors: list[Any] = []
341
+ async_exit_stack = request.scope.get("fastapi_inner_astack")
342
+ assert isinstance(async_exit_stack, AsyncExitStack), (
343
+ "fastapi_inner_astack not found in request scope"
344
+ )
345
+ solved_result = await solve_dependencies(
346
+ request=request,
347
+ dependant=dependant,
348
+ body=body,
349
+ dependency_overrides_provider=dependency_overrides_provider,
350
+ async_exit_stack=async_exit_stack,
351
+ embed_body_fields=embed_body_fields,
352
+ )
353
+ errors = solved_result.errors
354
+ if not errors:
355
+ raw_response = await run_endpoint_function(
356
+ dependant=dependant,
357
+ values=solved_result.values,
358
+ is_coroutine=is_coroutine,
359
+ )
360
+ if isinstance(raw_response, Response):
361
+ if raw_response.background is None:
362
+ raw_response.background = solved_result.background_tasks
363
+ response = raw_response
364
+ else:
365
+ response_args: dict[str, Any] = {
366
+ "background": solved_result.background_tasks
367
+ }
368
+ # If status_code was set, use it, otherwise use the default from the
369
+ # response class, in the case of redirect it's 307
370
+ current_status_code = (
371
+ status_code if status_code else solved_result.response.status_code
372
+ )
373
+ if current_status_code is not None:
374
+ response_args["status_code"] = current_status_code
375
+ if solved_result.response.status_code:
376
+ response_args["status_code"] = solved_result.response.status_code
377
+ content = await serialize_response(
378
+ field=response_field,
379
+ response_content=raw_response,
380
+ include=response_model_include,
381
+ exclude=response_model_exclude,
382
+ by_alias=response_model_by_alias,
383
+ exclude_unset=response_model_exclude_unset,
384
+ exclude_defaults=response_model_exclude_defaults,
385
+ exclude_none=response_model_exclude_none,
386
+ is_coroutine=is_coroutine,
387
+ endpoint_ctx=endpoint_ctx,
388
+ )
389
+ response = actual_response_class(content, **response_args)
390
+ if not is_body_allowed_for_status_code(response.status_code):
391
+ response.body = b""
392
+ response.headers.raw.extend(solved_result.response.headers.raw)
393
+ if errors:
394
+ validation_error = RequestValidationError(
395
+ errors, body=body, endpoint_ctx=endpoint_ctx
396
+ )
397
+ raise validation_error
398
+
399
+ # Return response
400
+ assert response
401
+ return response
402
+
403
+ return app
404
+
405
+
406
+ def get_websocket_app(
407
+ dependant: Dependant,
408
+ dependency_overrides_provider: Optional[Any] = None,
409
+ embed_body_fields: bool = False,
410
+ ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:
411
+ async def app(websocket: WebSocket) -> None:
412
+ endpoint_ctx = (
413
+ _extract_endpoint_context(dependant.call)
414
+ if dependant.call
415
+ else EndpointContext()
416
+ )
417
+ if dependant.path:
418
+ # For mounted sub-apps, include the mount path prefix
419
+ mount_path = websocket.scope.get("root_path", "").rstrip("/")
420
+ endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}"
421
+ async_exit_stack = websocket.scope.get("fastapi_inner_astack")
422
+ assert isinstance(async_exit_stack, AsyncExitStack), (
423
+ "fastapi_inner_astack not found in request scope"
424
+ )
425
+ solved_result = await solve_dependencies(
426
+ request=websocket,
427
+ dependant=dependant,
428
+ dependency_overrides_provider=dependency_overrides_provider,
429
+ async_exit_stack=async_exit_stack,
430
+ embed_body_fields=embed_body_fields,
431
+ )
432
+ if solved_result.errors:
433
+ raise WebSocketRequestValidationError(
434
+ solved_result.errors,
435
+ endpoint_ctx=endpoint_ctx,
436
+ )
437
+ assert dependant.call is not None, "dependant.call must be a function"
438
+ await dependant.call(**solved_result.values)
439
+
440
+ return app
441
+
442
+
443
+ class APIWebSocketRoute(routing.WebSocketRoute):
444
+ def __init__(
445
+ self,
446
+ path: str,
447
+ endpoint: Callable[..., Any],
448
+ *,
449
+ name: Optional[str] = None,
450
+ dependencies: Optional[Sequence[params.Depends]] = None,
451
+ dependency_overrides_provider: Optional[Any] = None,
452
+ ) -> None:
453
+ self.path = path
454
+ self.endpoint = endpoint
455
+ self.name = get_name(endpoint) if name is None else name
456
+ self.dependencies = list(dependencies or [])
457
+ self.path_regex, self.path_format, self.param_convertors = compile_path(path)
458
+ self.dependant = get_dependant(
459
+ path=self.path_format, call=self.endpoint, scope="function"
460
+ )
461
+ for depends in self.dependencies[::-1]:
462
+ self.dependant.dependencies.insert(
463
+ 0,
464
+ get_parameterless_sub_dependant(depends=depends, path=self.path_format),
465
+ )
466
+ self._flat_dependant = get_flat_dependant(self.dependant)
467
+ self._embed_body_fields = _should_embed_body_fields(
468
+ self._flat_dependant.body_params
469
+ )
470
+ self.app = websocket_session(
471
+ get_websocket_app(
472
+ dependant=self.dependant,
473
+ dependency_overrides_provider=dependency_overrides_provider,
474
+ embed_body_fields=self._embed_body_fields,
475
+ )
476
+ )
477
+
478
+ def matches(self, scope: Scope) -> tuple[Match, Scope]:
479
+ match, child_scope = super().matches(scope)
480
+ if match != Match.NONE:
481
+ child_scope["route"] = self
482
+ return match, child_scope
483
+
484
+
485
+ class APIRoute(routing.Route):
486
+ def __init__(
487
+ self,
488
+ path: str,
489
+ endpoint: Callable[..., Any],
490
+ *,
491
+ response_model: Any = Default(None),
492
+ status_code: Optional[int] = None,
493
+ tags: Optional[list[Union[str, Enum]]] = None,
494
+ dependencies: Optional[Sequence[params.Depends]] = None,
495
+ summary: Optional[str] = None,
496
+ description: Optional[str] = None,
497
+ response_description: str = "Successful Response",
498
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
499
+ deprecated: Optional[bool] = None,
500
+ name: Optional[str] = None,
501
+ methods: Optional[Union[set[str], list[str]]] = None,
502
+ operation_id: Optional[str] = None,
503
+ response_model_include: Optional[IncEx] = None,
504
+ response_model_exclude: Optional[IncEx] = None,
505
+ response_model_by_alias: bool = True,
506
+ response_model_exclude_unset: bool = False,
507
+ response_model_exclude_defaults: bool = False,
508
+ response_model_exclude_none: bool = False,
509
+ include_in_schema: bool = True,
510
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(
511
+ JSONResponse
512
+ ),
513
+ dependency_overrides_provider: Optional[Any] = None,
514
+ callbacks: Optional[list[BaseRoute]] = None,
515
+ openapi_extra: Optional[dict[str, Any]] = None,
516
+ generate_unique_id_function: Union[
517
+ Callable[["APIRoute"], str], DefaultPlaceholder
518
+ ] = Default(generate_unique_id),
519
+ ) -> None:
520
+ self.path = path
521
+ self.endpoint = endpoint
522
+ if isinstance(response_model, DefaultPlaceholder):
523
+ return_annotation = get_typed_return_annotation(endpoint)
524
+ if lenient_issubclass(return_annotation, Response):
525
+ response_model = None
526
+ else:
527
+ response_model = return_annotation
528
+ self.response_model = response_model
529
+ self.summary = summary
530
+ self.response_description = response_description
531
+ self.deprecated = deprecated
532
+ self.operation_id = operation_id
533
+ self.response_model_include = response_model_include
534
+ self.response_model_exclude = response_model_exclude
535
+ self.response_model_by_alias = response_model_by_alias
536
+ self.response_model_exclude_unset = response_model_exclude_unset
537
+ self.response_model_exclude_defaults = response_model_exclude_defaults
538
+ self.response_model_exclude_none = response_model_exclude_none
539
+ self.include_in_schema = include_in_schema
540
+ self.response_class = response_class
541
+ self.dependency_overrides_provider = dependency_overrides_provider
542
+ self.callbacks = callbacks
543
+ self.openapi_extra = openapi_extra
544
+ self.generate_unique_id_function = generate_unique_id_function
545
+ self.tags = tags or []
546
+ self.responses = responses or {}
547
+ self.name = get_name(endpoint) if name is None else name
548
+ self.path_regex, self.path_format, self.param_convertors = compile_path(path)
549
+ if methods is None:
550
+ methods = ["GET"]
551
+ self.methods: set[str] = {method.upper() for method in methods}
552
+ if isinstance(generate_unique_id_function, DefaultPlaceholder):
553
+ current_generate_unique_id: Callable[[APIRoute], str] = (
554
+ generate_unique_id_function.value
555
+ )
556
+ else:
557
+ current_generate_unique_id = generate_unique_id_function
558
+ self.unique_id = self.operation_id or current_generate_unique_id(self)
559
+ # normalize enums e.g. http.HTTPStatus
560
+ if isinstance(status_code, IntEnum):
561
+ status_code = int(status_code)
562
+ self.status_code = status_code
563
+ if self.response_model:
564
+ assert is_body_allowed_for_status_code(status_code), (
565
+ f"Status code {status_code} must not have a response body"
566
+ )
567
+ response_name = "Response_" + self.unique_id
568
+ if annotation_is_pydantic_v1(self.response_model):
569
+ raise PydanticV1NotSupportedError(
570
+ "pydantic.v1 models are no longer supported by FastAPI."
571
+ f" Please update the response model {self.response_model!r}."
572
+ )
573
+ self.response_field = create_model_field(
574
+ name=response_name,
575
+ type_=self.response_model,
576
+ mode="serialization",
577
+ )
578
+ # Create a clone of the field, so that a Pydantic submodel is not returned
579
+ # as is just because it's an instance of a subclass of a more limited class
580
+ # e.g. UserInDB (containing hashed_password) could be a subclass of User
581
+ # that doesn't have the hashed_password. But because it's a subclass, it
582
+ # would pass the validation and be returned as is.
583
+ # By being a new field, no inheritance will be passed as is. A new model
584
+ # will always be created.
585
+ # TODO: remove when deprecating Pydantic v1
586
+ self.secure_cloned_response_field: Optional[ModelField] = (
587
+ create_cloned_field(self.response_field)
588
+ )
589
+ else:
590
+ self.response_field = None # type: ignore
591
+ self.secure_cloned_response_field = None
592
+ self.dependencies = list(dependencies or [])
593
+ self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "")
594
+ # if a "form feed" character (page break) is found in the description text,
595
+ # truncate description text to the content preceding the first "form feed"
596
+ self.description = self.description.split("\f")[0].strip()
597
+ response_fields = {}
598
+ for additional_status_code, response in self.responses.items():
599
+ assert isinstance(response, dict), "An additional response must be a dict"
600
+ model = response.get("model")
601
+ if model:
602
+ assert is_body_allowed_for_status_code(additional_status_code), (
603
+ f"Status code {additional_status_code} must not have a response body"
604
+ )
605
+ response_name = f"Response_{additional_status_code}_{self.unique_id}"
606
+ if annotation_is_pydantic_v1(model):
607
+ raise PydanticV1NotSupportedError(
608
+ "pydantic.v1 models are no longer supported by FastAPI."
609
+ f" In responses={{}}, please update {model}."
610
+ )
611
+ response_field = create_model_field(
612
+ name=response_name, type_=model, mode="serialization"
613
+ )
614
+ response_fields[additional_status_code] = response_field
615
+ if response_fields:
616
+ self.response_fields: dict[Union[int, str], ModelField] = response_fields
617
+ else:
618
+ self.response_fields = {}
619
+
620
+ assert callable(endpoint), "An endpoint must be a callable"
621
+ self.dependant = get_dependant(
622
+ path=self.path_format, call=self.endpoint, scope="function"
623
+ )
624
+ for depends in self.dependencies[::-1]:
625
+ self.dependant.dependencies.insert(
626
+ 0,
627
+ get_parameterless_sub_dependant(depends=depends, path=self.path_format),
628
+ )
629
+ self._flat_dependant = get_flat_dependant(self.dependant)
630
+ self._embed_body_fields = _should_embed_body_fields(
631
+ self._flat_dependant.body_params
632
+ )
633
+ self.body_field = get_body_field(
634
+ flat_dependant=self._flat_dependant,
635
+ name=self.unique_id,
636
+ embed_body_fields=self._embed_body_fields,
637
+ )
638
+ self.app = request_response(self.get_route_handler())
639
+
640
+ def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:
641
+ return get_request_handler(
642
+ dependant=self.dependant,
643
+ body_field=self.body_field,
644
+ status_code=self.status_code,
645
+ response_class=self.response_class,
646
+ response_field=self.secure_cloned_response_field,
647
+ response_model_include=self.response_model_include,
648
+ response_model_exclude=self.response_model_exclude,
649
+ response_model_by_alias=self.response_model_by_alias,
650
+ response_model_exclude_unset=self.response_model_exclude_unset,
651
+ response_model_exclude_defaults=self.response_model_exclude_defaults,
652
+ response_model_exclude_none=self.response_model_exclude_none,
653
+ dependency_overrides_provider=self.dependency_overrides_provider,
654
+ embed_body_fields=self._embed_body_fields,
655
+ )
656
+
657
+ def matches(self, scope: Scope) -> tuple[Match, Scope]:
658
+ match, child_scope = super().matches(scope)
659
+ if match != Match.NONE:
660
+ child_scope["route"] = self
661
+ return match, child_scope
662
+
663
+
664
+ class APIRouter(routing.Router):
665
+ """
666
+ `APIRouter` class, used to group *path operations*, for example to structure
667
+ an app in multiple files. It would then be included in the `FastAPI` app, or
668
+ in another `APIRouter` (ultimately included in the app).
669
+
670
+ Read more about it in the
671
+ [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
672
+
673
+ ## Example
674
+
675
+ ```python
676
+ from fastapi import APIRouter, FastAPI
677
+
678
+ app = FastAPI()
679
+ router = APIRouter()
680
+
681
+
682
+ @router.get("/users/", tags=["users"])
683
+ async def read_users():
684
+ return [{"username": "Rick"}, {"username": "Morty"}]
685
+
686
+
687
+ app.include_router(router)
688
+ ```
689
+ """
690
+
691
+ def __init__(
692
+ self,
693
+ *,
694
+ prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
695
+ tags: Annotated[
696
+ Optional[list[Union[str, Enum]]],
697
+ Doc(
698
+ """
699
+ A list of tags to be applied to all the *path operations* in this
700
+ router.
701
+
702
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
703
+
704
+ Read more about it in the
705
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
706
+ """
707
+ ),
708
+ ] = None,
709
+ dependencies: Annotated[
710
+ Optional[Sequence[params.Depends]],
711
+ Doc(
712
+ """
713
+ A list of dependencies (using `Depends()`) to be applied to all the
714
+ *path operations* in this router.
715
+
716
+ Read more about it in the
717
+ [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
718
+ """
719
+ ),
720
+ ] = None,
721
+ default_response_class: Annotated[
722
+ type[Response],
723
+ Doc(
724
+ """
725
+ The default response class to be used.
726
+
727
+ Read more in the
728
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
729
+ """
730
+ ),
731
+ ] = Default(JSONResponse),
732
+ responses: Annotated[
733
+ Optional[dict[Union[int, str], dict[str, Any]]],
734
+ Doc(
735
+ """
736
+ Additional responses to be shown in OpenAPI.
737
+
738
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
739
+
740
+ Read more about it in the
741
+ [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
742
+
743
+ And in the
744
+ [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
745
+ """
746
+ ),
747
+ ] = None,
748
+ callbacks: Annotated[
749
+ Optional[list[BaseRoute]],
750
+ Doc(
751
+ """
752
+ OpenAPI callbacks that should apply to all *path operations* in this
753
+ router.
754
+
755
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
756
+
757
+ Read more about it in the
758
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
759
+ """
760
+ ),
761
+ ] = None,
762
+ routes: Annotated[
763
+ Optional[list[BaseRoute]],
764
+ Doc(
765
+ """
766
+ **Note**: you probably shouldn't use this parameter, it is inherited
767
+ from Starlette and supported for compatibility.
768
+
769
+ ---
770
+
771
+ A list of routes to serve incoming HTTP and WebSocket requests.
772
+ """
773
+ ),
774
+ deprecated(
775
+ """
776
+ You normally wouldn't use this parameter with FastAPI, it is inherited
777
+ from Starlette and supported for compatibility.
778
+
779
+ In FastAPI, you normally would use the *path operation methods*,
780
+ like `router.get()`, `router.post()`, etc.
781
+ """
782
+ ),
783
+ ] = None,
784
+ redirect_slashes: Annotated[
785
+ bool,
786
+ Doc(
787
+ """
788
+ Whether to detect and redirect slashes in URLs when the client doesn't
789
+ use the same format.
790
+ """
791
+ ),
792
+ ] = True,
793
+ default: Annotated[
794
+ Optional[ASGIApp],
795
+ Doc(
796
+ """
797
+ Default function handler for this router. Used to handle
798
+ 404 Not Found errors.
799
+ """
800
+ ),
801
+ ] = None,
802
+ dependency_overrides_provider: Annotated[
803
+ Optional[Any],
804
+ Doc(
805
+ """
806
+ Only used internally by FastAPI to handle dependency overrides.
807
+
808
+ You shouldn't need to use it. It normally points to the `FastAPI` app
809
+ object.
810
+ """
811
+ ),
812
+ ] = None,
813
+ route_class: Annotated[
814
+ type[APIRoute],
815
+ Doc(
816
+ """
817
+ Custom route (*path operation*) class to be used by this router.
818
+
819
+ Read more about it in the
820
+ [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).
821
+ """
822
+ ),
823
+ ] = APIRoute,
824
+ on_startup: Annotated[
825
+ Optional[Sequence[Callable[[], Any]]],
826
+ Doc(
827
+ """
828
+ A list of startup event handler functions.
829
+
830
+ You should instead use the `lifespan` handlers.
831
+
832
+ Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
833
+ """
834
+ ),
835
+ ] = None,
836
+ on_shutdown: Annotated[
837
+ Optional[Sequence[Callable[[], Any]]],
838
+ Doc(
839
+ """
840
+ A list of shutdown event handler functions.
841
+
842
+ You should instead use the `lifespan` handlers.
843
+
844
+ Read more in the
845
+ [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
846
+ """
847
+ ),
848
+ ] = None,
849
+ # the generic to Lifespan[AppType] is the type of the top level application
850
+ # which the router cannot know statically, so we use typing.Any
851
+ lifespan: Annotated[
852
+ Optional[Lifespan[Any]],
853
+ Doc(
854
+ """
855
+ A `Lifespan` context manager handler. This replaces `startup` and
856
+ `shutdown` functions with a single context manager.
857
+
858
+ Read more in the
859
+ [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
860
+ """
861
+ ),
862
+ ] = None,
863
+ deprecated: Annotated[
864
+ Optional[bool],
865
+ Doc(
866
+ """
867
+ Mark all *path operations* in this router as deprecated.
868
+
869
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
870
+
871
+ Read more about it in the
872
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
873
+ """
874
+ ),
875
+ ] = None,
876
+ include_in_schema: Annotated[
877
+ bool,
878
+ Doc(
879
+ """
880
+ To include (or not) all the *path operations* in this router in the
881
+ generated OpenAPI.
882
+
883
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
884
+
885
+ Read more about it in the
886
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
887
+ """
888
+ ),
889
+ ] = True,
890
+ generate_unique_id_function: Annotated[
891
+ Callable[[APIRoute], str],
892
+ Doc(
893
+ """
894
+ Customize the function used to generate unique IDs for the *path
895
+ operations* shown in the generated OpenAPI.
896
+
897
+ This is particularly useful when automatically generating clients or
898
+ SDKs for your API.
899
+
900
+ Read more about it in the
901
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
902
+ """
903
+ ),
904
+ ] = Default(generate_unique_id),
905
+ ) -> None:
906
+ super().__init__(
907
+ routes=routes,
908
+ redirect_slashes=redirect_slashes,
909
+ default=default,
910
+ on_startup=on_startup,
911
+ on_shutdown=on_shutdown,
912
+ lifespan=lifespan,
913
+ )
914
+ if prefix:
915
+ assert prefix.startswith("/"), "A path prefix must start with '/'"
916
+ assert not prefix.endswith("/"), (
917
+ "A path prefix must not end with '/', as the routes will start with '/'"
918
+ )
919
+ self.prefix = prefix
920
+ self.tags: list[Union[str, Enum]] = tags or []
921
+ self.dependencies = list(dependencies or [])
922
+ self.deprecated = deprecated
923
+ self.include_in_schema = include_in_schema
924
+ self.responses = responses or {}
925
+ self.callbacks = callbacks or []
926
+ self.dependency_overrides_provider = dependency_overrides_provider
927
+ self.route_class = route_class
928
+ self.default_response_class = default_response_class
929
+ self.generate_unique_id_function = generate_unique_id_function
930
+
931
+ def route(
932
+ self,
933
+ path: str,
934
+ methods: Optional[Collection[str]] = None,
935
+ name: Optional[str] = None,
936
+ include_in_schema: bool = True,
937
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
938
+ def decorator(func: DecoratedCallable) -> DecoratedCallable:
939
+ self.add_route(
940
+ path,
941
+ func,
942
+ methods=methods,
943
+ name=name,
944
+ include_in_schema=include_in_schema,
945
+ )
946
+ return func
947
+
948
+ return decorator
949
+
950
+ def add_api_route(
951
+ self,
952
+ path: str,
953
+ endpoint: Callable[..., Any],
954
+ *,
955
+ response_model: Any = Default(None),
956
+ status_code: Optional[int] = None,
957
+ tags: Optional[list[Union[str, Enum]]] = None,
958
+ dependencies: Optional[Sequence[params.Depends]] = None,
959
+ summary: Optional[str] = None,
960
+ description: Optional[str] = None,
961
+ response_description: str = "Successful Response",
962
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
963
+ deprecated: Optional[bool] = None,
964
+ methods: Optional[Union[set[str], list[str]]] = None,
965
+ operation_id: Optional[str] = None,
966
+ response_model_include: Optional[IncEx] = None,
967
+ response_model_exclude: Optional[IncEx] = None,
968
+ response_model_by_alias: bool = True,
969
+ response_model_exclude_unset: bool = False,
970
+ response_model_exclude_defaults: bool = False,
971
+ response_model_exclude_none: bool = False,
972
+ include_in_schema: bool = True,
973
+ response_class: Union[type[Response], DefaultPlaceholder] = Default(
974
+ JSONResponse
975
+ ),
976
+ name: Optional[str] = None,
977
+ route_class_override: Optional[type[APIRoute]] = None,
978
+ callbacks: Optional[list[BaseRoute]] = None,
979
+ openapi_extra: Optional[dict[str, Any]] = None,
980
+ generate_unique_id_function: Union[
981
+ Callable[[APIRoute], str], DefaultPlaceholder
982
+ ] = Default(generate_unique_id),
983
+ ) -> None:
984
+ route_class = route_class_override or self.route_class
985
+ responses = responses or {}
986
+ combined_responses = {**self.responses, **responses}
987
+ current_response_class = get_value_or_default(
988
+ response_class, self.default_response_class
989
+ )
990
+ current_tags = self.tags.copy()
991
+ if tags:
992
+ current_tags.extend(tags)
993
+ current_dependencies = self.dependencies.copy()
994
+ if dependencies:
995
+ current_dependencies.extend(dependencies)
996
+ current_callbacks = self.callbacks.copy()
997
+ if callbacks:
998
+ current_callbacks.extend(callbacks)
999
+ current_generate_unique_id = get_value_or_default(
1000
+ generate_unique_id_function, self.generate_unique_id_function
1001
+ )
1002
+ route = route_class(
1003
+ self.prefix + path,
1004
+ endpoint=endpoint,
1005
+ response_model=response_model,
1006
+ status_code=status_code,
1007
+ tags=current_tags,
1008
+ dependencies=current_dependencies,
1009
+ summary=summary,
1010
+ description=description,
1011
+ response_description=response_description,
1012
+ responses=combined_responses,
1013
+ deprecated=deprecated or self.deprecated,
1014
+ methods=methods,
1015
+ operation_id=operation_id,
1016
+ response_model_include=response_model_include,
1017
+ response_model_exclude=response_model_exclude,
1018
+ response_model_by_alias=response_model_by_alias,
1019
+ response_model_exclude_unset=response_model_exclude_unset,
1020
+ response_model_exclude_defaults=response_model_exclude_defaults,
1021
+ response_model_exclude_none=response_model_exclude_none,
1022
+ include_in_schema=include_in_schema and self.include_in_schema,
1023
+ response_class=current_response_class,
1024
+ name=name,
1025
+ dependency_overrides_provider=self.dependency_overrides_provider,
1026
+ callbacks=current_callbacks,
1027
+ openapi_extra=openapi_extra,
1028
+ generate_unique_id_function=current_generate_unique_id,
1029
+ )
1030
+ self.routes.append(route)
1031
+
1032
+ def api_route(
1033
+ self,
1034
+ path: str,
1035
+ *,
1036
+ response_model: Any = Default(None),
1037
+ status_code: Optional[int] = None,
1038
+ tags: Optional[list[Union[str, Enum]]] = None,
1039
+ dependencies: Optional[Sequence[params.Depends]] = None,
1040
+ summary: Optional[str] = None,
1041
+ description: Optional[str] = None,
1042
+ response_description: str = "Successful Response",
1043
+ responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
1044
+ deprecated: Optional[bool] = None,
1045
+ methods: Optional[list[str]] = None,
1046
+ operation_id: Optional[str] = None,
1047
+ response_model_include: Optional[IncEx] = None,
1048
+ response_model_exclude: Optional[IncEx] = None,
1049
+ response_model_by_alias: bool = True,
1050
+ response_model_exclude_unset: bool = False,
1051
+ response_model_exclude_defaults: bool = False,
1052
+ response_model_exclude_none: bool = False,
1053
+ include_in_schema: bool = True,
1054
+ response_class: type[Response] = Default(JSONResponse),
1055
+ name: Optional[str] = None,
1056
+ callbacks: Optional[list[BaseRoute]] = None,
1057
+ openapi_extra: Optional[dict[str, Any]] = None,
1058
+ generate_unique_id_function: Callable[[APIRoute], str] = Default(
1059
+ generate_unique_id
1060
+ ),
1061
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1062
+ def decorator(func: DecoratedCallable) -> DecoratedCallable:
1063
+ self.add_api_route(
1064
+ path,
1065
+ func,
1066
+ response_model=response_model,
1067
+ status_code=status_code,
1068
+ tags=tags,
1069
+ dependencies=dependencies,
1070
+ summary=summary,
1071
+ description=description,
1072
+ response_description=response_description,
1073
+ responses=responses,
1074
+ deprecated=deprecated,
1075
+ methods=methods,
1076
+ operation_id=operation_id,
1077
+ response_model_include=response_model_include,
1078
+ response_model_exclude=response_model_exclude,
1079
+ response_model_by_alias=response_model_by_alias,
1080
+ response_model_exclude_unset=response_model_exclude_unset,
1081
+ response_model_exclude_defaults=response_model_exclude_defaults,
1082
+ response_model_exclude_none=response_model_exclude_none,
1083
+ include_in_schema=include_in_schema,
1084
+ response_class=response_class,
1085
+ name=name,
1086
+ callbacks=callbacks,
1087
+ openapi_extra=openapi_extra,
1088
+ generate_unique_id_function=generate_unique_id_function,
1089
+ )
1090
+ return func
1091
+
1092
+ return decorator
1093
+
1094
+ def add_api_websocket_route(
1095
+ self,
1096
+ path: str,
1097
+ endpoint: Callable[..., Any],
1098
+ name: Optional[str] = None,
1099
+ *,
1100
+ dependencies: Optional[Sequence[params.Depends]] = None,
1101
+ ) -> None:
1102
+ current_dependencies = self.dependencies.copy()
1103
+ if dependencies:
1104
+ current_dependencies.extend(dependencies)
1105
+
1106
+ route = APIWebSocketRoute(
1107
+ self.prefix + path,
1108
+ endpoint=endpoint,
1109
+ name=name,
1110
+ dependencies=current_dependencies,
1111
+ dependency_overrides_provider=self.dependency_overrides_provider,
1112
+ )
1113
+ self.routes.append(route)
1114
+
1115
+ def websocket(
1116
+ self,
1117
+ path: Annotated[
1118
+ str,
1119
+ Doc(
1120
+ """
1121
+ WebSocket path.
1122
+ """
1123
+ ),
1124
+ ],
1125
+ name: Annotated[
1126
+ Optional[str],
1127
+ Doc(
1128
+ """
1129
+ A name for the WebSocket. Only used internally.
1130
+ """
1131
+ ),
1132
+ ] = None,
1133
+ *,
1134
+ dependencies: Annotated[
1135
+ Optional[Sequence[params.Depends]],
1136
+ Doc(
1137
+ """
1138
+ A list of dependencies (using `Depends()`) to be used for this
1139
+ WebSocket.
1140
+
1141
+ Read more about it in the
1142
+ [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
1143
+ """
1144
+ ),
1145
+ ] = None,
1146
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1147
+ """
1148
+ Decorate a WebSocket function.
1149
+
1150
+ Read more about it in the
1151
+ [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
1152
+
1153
+ **Example**
1154
+
1155
+ ## Example
1156
+
1157
+ ```python
1158
+ from fastapi import APIRouter, FastAPI, WebSocket
1159
+
1160
+ app = FastAPI()
1161
+ router = APIRouter()
1162
+
1163
+ @router.websocket("/ws")
1164
+ async def websocket_endpoint(websocket: WebSocket):
1165
+ await websocket.accept()
1166
+ while True:
1167
+ data = await websocket.receive_text()
1168
+ await websocket.send_text(f"Message text was: {data}")
1169
+
1170
+ app.include_router(router)
1171
+ ```
1172
+ """
1173
+
1174
+ def decorator(func: DecoratedCallable) -> DecoratedCallable:
1175
+ self.add_api_websocket_route(
1176
+ path, func, name=name, dependencies=dependencies
1177
+ )
1178
+ return func
1179
+
1180
+ return decorator
1181
+
1182
+ def websocket_route(
1183
+ self, path: str, name: Union[str, None] = None
1184
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1185
+ def decorator(func: DecoratedCallable) -> DecoratedCallable:
1186
+ self.add_websocket_route(path, func, name=name)
1187
+ return func
1188
+
1189
+ return decorator
1190
+
1191
+ def include_router(
1192
+ self,
1193
+ router: Annotated["APIRouter", Doc("The `APIRouter` to include.")],
1194
+ *,
1195
+ prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
1196
+ tags: Annotated[
1197
+ Optional[list[Union[str, Enum]]],
1198
+ Doc(
1199
+ """
1200
+ A list of tags to be applied to all the *path operations* in this
1201
+ router.
1202
+
1203
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1204
+
1205
+ Read more about it in the
1206
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1207
+ """
1208
+ ),
1209
+ ] = None,
1210
+ dependencies: Annotated[
1211
+ Optional[Sequence[params.Depends]],
1212
+ Doc(
1213
+ """
1214
+ A list of dependencies (using `Depends()`) to be applied to all the
1215
+ *path operations* in this router.
1216
+
1217
+ Read more about it in the
1218
+ [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
1219
+ """
1220
+ ),
1221
+ ] = None,
1222
+ default_response_class: Annotated[
1223
+ type[Response],
1224
+ Doc(
1225
+ """
1226
+ The default response class to be used.
1227
+
1228
+ Read more in the
1229
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
1230
+ """
1231
+ ),
1232
+ ] = Default(JSONResponse),
1233
+ responses: Annotated[
1234
+ Optional[dict[Union[int, str], dict[str, Any]]],
1235
+ Doc(
1236
+ """
1237
+ Additional responses to be shown in OpenAPI.
1238
+
1239
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1240
+
1241
+ Read more about it in the
1242
+ [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
1243
+
1244
+ And in the
1245
+ [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
1246
+ """
1247
+ ),
1248
+ ] = None,
1249
+ callbacks: Annotated[
1250
+ Optional[list[BaseRoute]],
1251
+ Doc(
1252
+ """
1253
+ OpenAPI callbacks that should apply to all *path operations* in this
1254
+ router.
1255
+
1256
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1257
+
1258
+ Read more about it in the
1259
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
1260
+ """
1261
+ ),
1262
+ ] = None,
1263
+ deprecated: Annotated[
1264
+ Optional[bool],
1265
+ Doc(
1266
+ """
1267
+ Mark all *path operations* in this router as deprecated.
1268
+
1269
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1270
+
1271
+ Read more about it in the
1272
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1273
+ """
1274
+ ),
1275
+ ] = None,
1276
+ include_in_schema: Annotated[
1277
+ bool,
1278
+ Doc(
1279
+ """
1280
+ Include (or not) all the *path operations* in this router in the
1281
+ generated OpenAPI schema.
1282
+
1283
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
1284
+ """
1285
+ ),
1286
+ ] = True,
1287
+ generate_unique_id_function: Annotated[
1288
+ Callable[[APIRoute], str],
1289
+ Doc(
1290
+ """
1291
+ Customize the function used to generate unique IDs for the *path
1292
+ operations* shown in the generated OpenAPI.
1293
+
1294
+ This is particularly useful when automatically generating clients or
1295
+ SDKs for your API.
1296
+
1297
+ Read more about it in the
1298
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1299
+ """
1300
+ ),
1301
+ ] = Default(generate_unique_id),
1302
+ ) -> None:
1303
+ """
1304
+ Include another `APIRouter` in the same current `APIRouter`.
1305
+
1306
+ Read more about it in the
1307
+ [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
1308
+
1309
+ ## Example
1310
+
1311
+ ```python
1312
+ from fastapi import APIRouter, FastAPI
1313
+
1314
+ app = FastAPI()
1315
+ internal_router = APIRouter()
1316
+ users_router = APIRouter()
1317
+
1318
+ @users_router.get("/users/")
1319
+ def read_users():
1320
+ return [{"name": "Rick"}, {"name": "Morty"}]
1321
+
1322
+ internal_router.include_router(users_router)
1323
+ app.include_router(internal_router)
1324
+ ```
1325
+ """
1326
+ if prefix:
1327
+ assert prefix.startswith("/"), "A path prefix must start with '/'"
1328
+ assert not prefix.endswith("/"), (
1329
+ "A path prefix must not end with '/', as the routes will start with '/'"
1330
+ )
1331
+ else:
1332
+ for r in router.routes:
1333
+ path = getattr(r, "path") # noqa: B009
1334
+ name = getattr(r, "name", "unknown")
1335
+ if path is not None and not path:
1336
+ raise FastAPIError(
1337
+ f"Prefix and path cannot be both empty (path operation: {name})"
1338
+ )
1339
+ if responses is None:
1340
+ responses = {}
1341
+ for route in router.routes:
1342
+ if isinstance(route, APIRoute):
1343
+ combined_responses = {**responses, **route.responses}
1344
+ use_response_class = get_value_or_default(
1345
+ route.response_class,
1346
+ router.default_response_class,
1347
+ default_response_class,
1348
+ self.default_response_class,
1349
+ )
1350
+ current_tags = []
1351
+ if tags:
1352
+ current_tags.extend(tags)
1353
+ if route.tags:
1354
+ current_tags.extend(route.tags)
1355
+ current_dependencies: list[params.Depends] = []
1356
+ if dependencies:
1357
+ current_dependencies.extend(dependencies)
1358
+ if route.dependencies:
1359
+ current_dependencies.extend(route.dependencies)
1360
+ current_callbacks = []
1361
+ if callbacks:
1362
+ current_callbacks.extend(callbacks)
1363
+ if route.callbacks:
1364
+ current_callbacks.extend(route.callbacks)
1365
+ current_generate_unique_id = get_value_or_default(
1366
+ route.generate_unique_id_function,
1367
+ router.generate_unique_id_function,
1368
+ generate_unique_id_function,
1369
+ self.generate_unique_id_function,
1370
+ )
1371
+ self.add_api_route(
1372
+ prefix + route.path,
1373
+ route.endpoint,
1374
+ response_model=route.response_model,
1375
+ status_code=route.status_code,
1376
+ tags=current_tags,
1377
+ dependencies=current_dependencies,
1378
+ summary=route.summary,
1379
+ description=route.description,
1380
+ response_description=route.response_description,
1381
+ responses=combined_responses,
1382
+ deprecated=route.deprecated or deprecated or self.deprecated,
1383
+ methods=route.methods,
1384
+ operation_id=route.operation_id,
1385
+ response_model_include=route.response_model_include,
1386
+ response_model_exclude=route.response_model_exclude,
1387
+ response_model_by_alias=route.response_model_by_alias,
1388
+ response_model_exclude_unset=route.response_model_exclude_unset,
1389
+ response_model_exclude_defaults=route.response_model_exclude_defaults,
1390
+ response_model_exclude_none=route.response_model_exclude_none,
1391
+ include_in_schema=route.include_in_schema
1392
+ and self.include_in_schema
1393
+ and include_in_schema,
1394
+ response_class=use_response_class,
1395
+ name=route.name,
1396
+ route_class_override=type(route),
1397
+ callbacks=current_callbacks,
1398
+ openapi_extra=route.openapi_extra,
1399
+ generate_unique_id_function=current_generate_unique_id,
1400
+ )
1401
+ elif isinstance(route, routing.Route):
1402
+ methods = list(route.methods or [])
1403
+ self.add_route(
1404
+ prefix + route.path,
1405
+ route.endpoint,
1406
+ methods=methods,
1407
+ include_in_schema=route.include_in_schema,
1408
+ name=route.name,
1409
+ )
1410
+ elif isinstance(route, APIWebSocketRoute):
1411
+ current_dependencies = []
1412
+ if dependencies:
1413
+ current_dependencies.extend(dependencies)
1414
+ if route.dependencies:
1415
+ current_dependencies.extend(route.dependencies)
1416
+ self.add_api_websocket_route(
1417
+ prefix + route.path,
1418
+ route.endpoint,
1419
+ dependencies=current_dependencies,
1420
+ name=route.name,
1421
+ )
1422
+ elif isinstance(route, routing.WebSocketRoute):
1423
+ self.add_websocket_route(
1424
+ prefix + route.path, route.endpoint, name=route.name
1425
+ )
1426
+ for handler in router.on_startup:
1427
+ self.add_event_handler("startup", handler)
1428
+ for handler in router.on_shutdown:
1429
+ self.add_event_handler("shutdown", handler)
1430
+ self.lifespan_context = _merge_lifespan_context(
1431
+ self.lifespan_context,
1432
+ router.lifespan_context,
1433
+ )
1434
+
1435
+ def get(
1436
+ self,
1437
+ path: Annotated[
1438
+ str,
1439
+ Doc(
1440
+ """
1441
+ The URL path to be used for this *path operation*.
1442
+
1443
+ For example, in `http://example.com/items`, the path is `/items`.
1444
+ """
1445
+ ),
1446
+ ],
1447
+ *,
1448
+ response_model: Annotated[
1449
+ Any,
1450
+ Doc(
1451
+ """
1452
+ The type to use for the response.
1453
+
1454
+ It could be any valid Pydantic *field* type. So, it doesn't have to
1455
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
1456
+ etc.
1457
+
1458
+ It will be used for:
1459
+
1460
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
1461
+ show it as the response (JSON Schema).
1462
+ * Serialization: you could return an arbitrary object and the
1463
+ `response_model` would be used to serialize that object into the
1464
+ corresponding JSON.
1465
+ * Filtering: the JSON sent to the client will only contain the data
1466
+ (fields) defined in the `response_model`. If you returned an object
1467
+ that contains an attribute `password` but the `response_model` does
1468
+ not include that field, the JSON sent to the client would not have
1469
+ that `password`.
1470
+ * Validation: whatever you return will be serialized with the
1471
+ `response_model`, converting any data as necessary to generate the
1472
+ corresponding JSON. But if the data in the object returned is not
1473
+ valid, that would mean a violation of the contract with the client,
1474
+ so it's an error from the API developer. So, FastAPI will raise an
1475
+ error and return a 500 error code (Internal Server Error).
1476
+
1477
+ Read more about it in the
1478
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
1479
+ """
1480
+ ),
1481
+ ] = Default(None),
1482
+ status_code: Annotated[
1483
+ Optional[int],
1484
+ Doc(
1485
+ """
1486
+ The default status code to be used for the response.
1487
+
1488
+ You could override the status code by returning a response directly.
1489
+
1490
+ Read more about it in the
1491
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
1492
+ """
1493
+ ),
1494
+ ] = None,
1495
+ tags: Annotated[
1496
+ Optional[list[Union[str, Enum]]],
1497
+ Doc(
1498
+ """
1499
+ A list of tags to be applied to the *path operation*.
1500
+
1501
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1502
+
1503
+ Read more about it in the
1504
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
1505
+ """
1506
+ ),
1507
+ ] = None,
1508
+ dependencies: Annotated[
1509
+ Optional[Sequence[params.Depends]],
1510
+ Doc(
1511
+ """
1512
+ A list of dependencies (using `Depends()`) to be applied to the
1513
+ *path operation*.
1514
+
1515
+ Read more about it in the
1516
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
1517
+ """
1518
+ ),
1519
+ ] = None,
1520
+ summary: Annotated[
1521
+ Optional[str],
1522
+ Doc(
1523
+ """
1524
+ A summary for the *path operation*.
1525
+
1526
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1527
+
1528
+ Read more about it in the
1529
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1530
+ """
1531
+ ),
1532
+ ] = None,
1533
+ description: Annotated[
1534
+ Optional[str],
1535
+ Doc(
1536
+ """
1537
+ A description for the *path operation*.
1538
+
1539
+ If not provided, it will be extracted automatically from the docstring
1540
+ of the *path operation function*.
1541
+
1542
+ It can contain Markdown.
1543
+
1544
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1545
+
1546
+ Read more about it in the
1547
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1548
+ """
1549
+ ),
1550
+ ] = None,
1551
+ response_description: Annotated[
1552
+ str,
1553
+ Doc(
1554
+ """
1555
+ The description for the default response.
1556
+
1557
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1558
+ """
1559
+ ),
1560
+ ] = "Successful Response",
1561
+ responses: Annotated[
1562
+ Optional[dict[Union[int, str], dict[str, Any]]],
1563
+ Doc(
1564
+ """
1565
+ Additional responses that could be returned by this *path operation*.
1566
+
1567
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1568
+ """
1569
+ ),
1570
+ ] = None,
1571
+ deprecated: Annotated[
1572
+ Optional[bool],
1573
+ Doc(
1574
+ """
1575
+ Mark this *path operation* as deprecated.
1576
+
1577
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1578
+ """
1579
+ ),
1580
+ ] = None,
1581
+ operation_id: Annotated[
1582
+ Optional[str],
1583
+ Doc(
1584
+ """
1585
+ Custom operation ID to be used by this *path operation*.
1586
+
1587
+ By default, it is generated automatically.
1588
+
1589
+ If you provide a custom operation ID, you need to make sure it is
1590
+ unique for the whole API.
1591
+
1592
+ You can customize the
1593
+ operation ID generation with the parameter
1594
+ `generate_unique_id_function` in the `FastAPI` class.
1595
+
1596
+ Read more about it in the
1597
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1598
+ """
1599
+ ),
1600
+ ] = None,
1601
+ response_model_include: Annotated[
1602
+ Optional[IncEx],
1603
+ Doc(
1604
+ """
1605
+ Configuration passed to Pydantic to include only certain fields in the
1606
+ response data.
1607
+
1608
+ Read more about it in the
1609
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1610
+ """
1611
+ ),
1612
+ ] = None,
1613
+ response_model_exclude: Annotated[
1614
+ Optional[IncEx],
1615
+ Doc(
1616
+ """
1617
+ Configuration passed to Pydantic to exclude certain fields in the
1618
+ response data.
1619
+
1620
+ Read more about it in the
1621
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1622
+ """
1623
+ ),
1624
+ ] = None,
1625
+ response_model_by_alias: Annotated[
1626
+ bool,
1627
+ Doc(
1628
+ """
1629
+ Configuration passed to Pydantic to define if the response model
1630
+ should be serialized by alias when an alias is used.
1631
+
1632
+ Read more about it in the
1633
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1634
+ """
1635
+ ),
1636
+ ] = True,
1637
+ response_model_exclude_unset: Annotated[
1638
+ bool,
1639
+ Doc(
1640
+ """
1641
+ Configuration passed to Pydantic to define if the response data
1642
+ should have all the fields, including the ones that were not set and
1643
+ have their default values. This is different from
1644
+ `response_model_exclude_defaults` in that if the fields are set,
1645
+ they will be included in the response, even if the value is the same
1646
+ as the default.
1647
+
1648
+ When `True`, default values are omitted from the response.
1649
+
1650
+ Read more about it in the
1651
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
1652
+ """
1653
+ ),
1654
+ ] = False,
1655
+ response_model_exclude_defaults: Annotated[
1656
+ bool,
1657
+ Doc(
1658
+ """
1659
+ Configuration passed to Pydantic to define if the response data
1660
+ should have all the fields, including the ones that have the same value
1661
+ as the default. This is different from `response_model_exclude_unset`
1662
+ in that if the fields are set but contain the same default values,
1663
+ they will be excluded from the response.
1664
+
1665
+ When `True`, default values are omitted from the response.
1666
+
1667
+ Read more about it in the
1668
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
1669
+ """
1670
+ ),
1671
+ ] = False,
1672
+ response_model_exclude_none: Annotated[
1673
+ bool,
1674
+ Doc(
1675
+ """
1676
+ Configuration passed to Pydantic to define if the response data should
1677
+ exclude fields set to `None`.
1678
+
1679
+ This is much simpler (less smart) than `response_model_exclude_unset`
1680
+ and `response_model_exclude_defaults`. You probably want to use one of
1681
+ those two instead of this one, as those allow returning `None` values
1682
+ when it makes sense.
1683
+
1684
+ Read more about it in the
1685
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
1686
+ """
1687
+ ),
1688
+ ] = False,
1689
+ include_in_schema: Annotated[
1690
+ bool,
1691
+ Doc(
1692
+ """
1693
+ Include this *path operation* in the generated OpenAPI schema.
1694
+
1695
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
1696
+
1697
+ Read more about it in the
1698
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
1699
+ """
1700
+ ),
1701
+ ] = True,
1702
+ response_class: Annotated[
1703
+ type[Response],
1704
+ Doc(
1705
+ """
1706
+ Response class to be used for this *path operation*.
1707
+
1708
+ This will not be used if you return a response directly.
1709
+
1710
+ Read more about it in the
1711
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
1712
+ """
1713
+ ),
1714
+ ] = Default(JSONResponse),
1715
+ name: Annotated[
1716
+ Optional[str],
1717
+ Doc(
1718
+ """
1719
+ Name for this *path operation*. Only used internally.
1720
+ """
1721
+ ),
1722
+ ] = None,
1723
+ callbacks: Annotated[
1724
+ Optional[list[BaseRoute]],
1725
+ Doc(
1726
+ """
1727
+ List of *path operations* that will be used as OpenAPI callbacks.
1728
+
1729
+ This is only for OpenAPI documentation, the callbacks won't be used
1730
+ directly.
1731
+
1732
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1733
+
1734
+ Read more about it in the
1735
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
1736
+ """
1737
+ ),
1738
+ ] = None,
1739
+ openapi_extra: Annotated[
1740
+ Optional[dict[str, Any]],
1741
+ Doc(
1742
+ """
1743
+ Extra metadata to be included in the OpenAPI schema for this *path
1744
+ operation*.
1745
+
1746
+ Read more about it in the
1747
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
1748
+ """
1749
+ ),
1750
+ ] = None,
1751
+ generate_unique_id_function: Annotated[
1752
+ Callable[[APIRoute], str],
1753
+ Doc(
1754
+ """
1755
+ Customize the function used to generate unique IDs for the *path
1756
+ operations* shown in the generated OpenAPI.
1757
+
1758
+ This is particularly useful when automatically generating clients or
1759
+ SDKs for your API.
1760
+
1761
+ Read more about it in the
1762
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1763
+ """
1764
+ ),
1765
+ ] = Default(generate_unique_id),
1766
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1767
+ """
1768
+ Add a *path operation* using an HTTP GET operation.
1769
+
1770
+ ## Example
1771
+
1772
+ ```python
1773
+ from fastapi import APIRouter, FastAPI
1774
+
1775
+ app = FastAPI()
1776
+ router = APIRouter()
1777
+
1778
+ @router.get("/items/")
1779
+ def read_items():
1780
+ return [{"name": "Empanada"}, {"name": "Arepa"}]
1781
+
1782
+ app.include_router(router)
1783
+ ```
1784
+ """
1785
+ return self.api_route(
1786
+ path=path,
1787
+ response_model=response_model,
1788
+ status_code=status_code,
1789
+ tags=tags,
1790
+ dependencies=dependencies,
1791
+ summary=summary,
1792
+ description=description,
1793
+ response_description=response_description,
1794
+ responses=responses,
1795
+ deprecated=deprecated,
1796
+ methods=["GET"],
1797
+ operation_id=operation_id,
1798
+ response_model_include=response_model_include,
1799
+ response_model_exclude=response_model_exclude,
1800
+ response_model_by_alias=response_model_by_alias,
1801
+ response_model_exclude_unset=response_model_exclude_unset,
1802
+ response_model_exclude_defaults=response_model_exclude_defaults,
1803
+ response_model_exclude_none=response_model_exclude_none,
1804
+ include_in_schema=include_in_schema,
1805
+ response_class=response_class,
1806
+ name=name,
1807
+ callbacks=callbacks,
1808
+ openapi_extra=openapi_extra,
1809
+ generate_unique_id_function=generate_unique_id_function,
1810
+ )
1811
+
1812
+ def put(
1813
+ self,
1814
+ path: Annotated[
1815
+ str,
1816
+ Doc(
1817
+ """
1818
+ The URL path to be used for this *path operation*.
1819
+
1820
+ For example, in `http://example.com/items`, the path is `/items`.
1821
+ """
1822
+ ),
1823
+ ],
1824
+ *,
1825
+ response_model: Annotated[
1826
+ Any,
1827
+ Doc(
1828
+ """
1829
+ The type to use for the response.
1830
+
1831
+ It could be any valid Pydantic *field* type. So, it doesn't have to
1832
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
1833
+ etc.
1834
+
1835
+ It will be used for:
1836
+
1837
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
1838
+ show it as the response (JSON Schema).
1839
+ * Serialization: you could return an arbitrary object and the
1840
+ `response_model` would be used to serialize that object into the
1841
+ corresponding JSON.
1842
+ * Filtering: the JSON sent to the client will only contain the data
1843
+ (fields) defined in the `response_model`. If you returned an object
1844
+ that contains an attribute `password` but the `response_model` does
1845
+ not include that field, the JSON sent to the client would not have
1846
+ that `password`.
1847
+ * Validation: whatever you return will be serialized with the
1848
+ `response_model`, converting any data as necessary to generate the
1849
+ corresponding JSON. But if the data in the object returned is not
1850
+ valid, that would mean a violation of the contract with the client,
1851
+ so it's an error from the API developer. So, FastAPI will raise an
1852
+ error and return a 500 error code (Internal Server Error).
1853
+
1854
+ Read more about it in the
1855
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
1856
+ """
1857
+ ),
1858
+ ] = Default(None),
1859
+ status_code: Annotated[
1860
+ Optional[int],
1861
+ Doc(
1862
+ """
1863
+ The default status code to be used for the response.
1864
+
1865
+ You could override the status code by returning a response directly.
1866
+
1867
+ Read more about it in the
1868
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
1869
+ """
1870
+ ),
1871
+ ] = None,
1872
+ tags: Annotated[
1873
+ Optional[list[Union[str, Enum]]],
1874
+ Doc(
1875
+ """
1876
+ A list of tags to be applied to the *path operation*.
1877
+
1878
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1879
+
1880
+ Read more about it in the
1881
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
1882
+ """
1883
+ ),
1884
+ ] = None,
1885
+ dependencies: Annotated[
1886
+ Optional[Sequence[params.Depends]],
1887
+ Doc(
1888
+ """
1889
+ A list of dependencies (using `Depends()`) to be applied to the
1890
+ *path operation*.
1891
+
1892
+ Read more about it in the
1893
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
1894
+ """
1895
+ ),
1896
+ ] = None,
1897
+ summary: Annotated[
1898
+ Optional[str],
1899
+ Doc(
1900
+ """
1901
+ A summary for the *path operation*.
1902
+
1903
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1904
+
1905
+ Read more about it in the
1906
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1907
+ """
1908
+ ),
1909
+ ] = None,
1910
+ description: Annotated[
1911
+ Optional[str],
1912
+ Doc(
1913
+ """
1914
+ A description for the *path operation*.
1915
+
1916
+ If not provided, it will be extracted automatically from the docstring
1917
+ of the *path operation function*.
1918
+
1919
+ It can contain Markdown.
1920
+
1921
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1922
+
1923
+ Read more about it in the
1924
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1925
+ """
1926
+ ),
1927
+ ] = None,
1928
+ response_description: Annotated[
1929
+ str,
1930
+ Doc(
1931
+ """
1932
+ The description for the default response.
1933
+
1934
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1935
+ """
1936
+ ),
1937
+ ] = "Successful Response",
1938
+ responses: Annotated[
1939
+ Optional[dict[Union[int, str], dict[str, Any]]],
1940
+ Doc(
1941
+ """
1942
+ Additional responses that could be returned by this *path operation*.
1943
+
1944
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1945
+ """
1946
+ ),
1947
+ ] = None,
1948
+ deprecated: Annotated[
1949
+ Optional[bool],
1950
+ Doc(
1951
+ """
1952
+ Mark this *path operation* as deprecated.
1953
+
1954
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1955
+ """
1956
+ ),
1957
+ ] = None,
1958
+ operation_id: Annotated[
1959
+ Optional[str],
1960
+ Doc(
1961
+ """
1962
+ Custom operation ID to be used by this *path operation*.
1963
+
1964
+ By default, it is generated automatically.
1965
+
1966
+ If you provide a custom operation ID, you need to make sure it is
1967
+ unique for the whole API.
1968
+
1969
+ You can customize the
1970
+ operation ID generation with the parameter
1971
+ `generate_unique_id_function` in the `FastAPI` class.
1972
+
1973
+ Read more about it in the
1974
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1975
+ """
1976
+ ),
1977
+ ] = None,
1978
+ response_model_include: Annotated[
1979
+ Optional[IncEx],
1980
+ Doc(
1981
+ """
1982
+ Configuration passed to Pydantic to include only certain fields in the
1983
+ response data.
1984
+
1985
+ Read more about it in the
1986
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1987
+ """
1988
+ ),
1989
+ ] = None,
1990
+ response_model_exclude: Annotated[
1991
+ Optional[IncEx],
1992
+ Doc(
1993
+ """
1994
+ Configuration passed to Pydantic to exclude certain fields in the
1995
+ response data.
1996
+
1997
+ Read more about it in the
1998
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1999
+ """
2000
+ ),
2001
+ ] = None,
2002
+ response_model_by_alias: Annotated[
2003
+ bool,
2004
+ Doc(
2005
+ """
2006
+ Configuration passed to Pydantic to define if the response model
2007
+ should be serialized by alias when an alias is used.
2008
+
2009
+ Read more about it in the
2010
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2011
+ """
2012
+ ),
2013
+ ] = True,
2014
+ response_model_exclude_unset: Annotated[
2015
+ bool,
2016
+ Doc(
2017
+ """
2018
+ Configuration passed to Pydantic to define if the response data
2019
+ should have all the fields, including the ones that were not set and
2020
+ have their default values. This is different from
2021
+ `response_model_exclude_defaults` in that if the fields are set,
2022
+ they will be included in the response, even if the value is the same
2023
+ as the default.
2024
+
2025
+ When `True`, default values are omitted from the response.
2026
+
2027
+ Read more about it in the
2028
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2029
+ """
2030
+ ),
2031
+ ] = False,
2032
+ response_model_exclude_defaults: Annotated[
2033
+ bool,
2034
+ Doc(
2035
+ """
2036
+ Configuration passed to Pydantic to define if the response data
2037
+ should have all the fields, including the ones that have the same value
2038
+ as the default. This is different from `response_model_exclude_unset`
2039
+ in that if the fields are set but contain the same default values,
2040
+ they will be excluded from the response.
2041
+
2042
+ When `True`, default values are omitted from the response.
2043
+
2044
+ Read more about it in the
2045
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2046
+ """
2047
+ ),
2048
+ ] = False,
2049
+ response_model_exclude_none: Annotated[
2050
+ bool,
2051
+ Doc(
2052
+ """
2053
+ Configuration passed to Pydantic to define if the response data should
2054
+ exclude fields set to `None`.
2055
+
2056
+ This is much simpler (less smart) than `response_model_exclude_unset`
2057
+ and `response_model_exclude_defaults`. You probably want to use one of
2058
+ those two instead of this one, as those allow returning `None` values
2059
+ when it makes sense.
2060
+
2061
+ Read more about it in the
2062
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
2063
+ """
2064
+ ),
2065
+ ] = False,
2066
+ include_in_schema: Annotated[
2067
+ bool,
2068
+ Doc(
2069
+ """
2070
+ Include this *path operation* in the generated OpenAPI schema.
2071
+
2072
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
2073
+
2074
+ Read more about it in the
2075
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
2076
+ """
2077
+ ),
2078
+ ] = True,
2079
+ response_class: Annotated[
2080
+ type[Response],
2081
+ Doc(
2082
+ """
2083
+ Response class to be used for this *path operation*.
2084
+
2085
+ This will not be used if you return a response directly.
2086
+
2087
+ Read more about it in the
2088
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
2089
+ """
2090
+ ),
2091
+ ] = Default(JSONResponse),
2092
+ name: Annotated[
2093
+ Optional[str],
2094
+ Doc(
2095
+ """
2096
+ Name for this *path operation*. Only used internally.
2097
+ """
2098
+ ),
2099
+ ] = None,
2100
+ callbacks: Annotated[
2101
+ Optional[list[BaseRoute]],
2102
+ Doc(
2103
+ """
2104
+ List of *path operations* that will be used as OpenAPI callbacks.
2105
+
2106
+ This is only for OpenAPI documentation, the callbacks won't be used
2107
+ directly.
2108
+
2109
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2110
+
2111
+ Read more about it in the
2112
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
2113
+ """
2114
+ ),
2115
+ ] = None,
2116
+ openapi_extra: Annotated[
2117
+ Optional[dict[str, Any]],
2118
+ Doc(
2119
+ """
2120
+ Extra metadata to be included in the OpenAPI schema for this *path
2121
+ operation*.
2122
+
2123
+ Read more about it in the
2124
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
2125
+ """
2126
+ ),
2127
+ ] = None,
2128
+ generate_unique_id_function: Annotated[
2129
+ Callable[[APIRoute], str],
2130
+ Doc(
2131
+ """
2132
+ Customize the function used to generate unique IDs for the *path
2133
+ operations* shown in the generated OpenAPI.
2134
+
2135
+ This is particularly useful when automatically generating clients or
2136
+ SDKs for your API.
2137
+
2138
+ Read more about it in the
2139
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2140
+ """
2141
+ ),
2142
+ ] = Default(generate_unique_id),
2143
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
2144
+ """
2145
+ Add a *path operation* using an HTTP PUT operation.
2146
+
2147
+ ## Example
2148
+
2149
+ ```python
2150
+ from fastapi import APIRouter, FastAPI
2151
+ from pydantic import BaseModel
2152
+
2153
+ class Item(BaseModel):
2154
+ name: str
2155
+ description: str | None = None
2156
+
2157
+ app = FastAPI()
2158
+ router = APIRouter()
2159
+
2160
+ @router.put("/items/{item_id}")
2161
+ def replace_item(item_id: str, item: Item):
2162
+ return {"message": "Item replaced", "id": item_id}
2163
+
2164
+ app.include_router(router)
2165
+ ```
2166
+ """
2167
+ return self.api_route(
2168
+ path=path,
2169
+ response_model=response_model,
2170
+ status_code=status_code,
2171
+ tags=tags,
2172
+ dependencies=dependencies,
2173
+ summary=summary,
2174
+ description=description,
2175
+ response_description=response_description,
2176
+ responses=responses,
2177
+ deprecated=deprecated,
2178
+ methods=["PUT"],
2179
+ operation_id=operation_id,
2180
+ response_model_include=response_model_include,
2181
+ response_model_exclude=response_model_exclude,
2182
+ response_model_by_alias=response_model_by_alias,
2183
+ response_model_exclude_unset=response_model_exclude_unset,
2184
+ response_model_exclude_defaults=response_model_exclude_defaults,
2185
+ response_model_exclude_none=response_model_exclude_none,
2186
+ include_in_schema=include_in_schema,
2187
+ response_class=response_class,
2188
+ name=name,
2189
+ callbacks=callbacks,
2190
+ openapi_extra=openapi_extra,
2191
+ generate_unique_id_function=generate_unique_id_function,
2192
+ )
2193
+
2194
+ def post(
2195
+ self,
2196
+ path: Annotated[
2197
+ str,
2198
+ Doc(
2199
+ """
2200
+ The URL path to be used for this *path operation*.
2201
+
2202
+ For example, in `http://example.com/items`, the path is `/items`.
2203
+ """
2204
+ ),
2205
+ ],
2206
+ *,
2207
+ response_model: Annotated[
2208
+ Any,
2209
+ Doc(
2210
+ """
2211
+ The type to use for the response.
2212
+
2213
+ It could be any valid Pydantic *field* type. So, it doesn't have to
2214
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
2215
+ etc.
2216
+
2217
+ It will be used for:
2218
+
2219
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
2220
+ show it as the response (JSON Schema).
2221
+ * Serialization: you could return an arbitrary object and the
2222
+ `response_model` would be used to serialize that object into the
2223
+ corresponding JSON.
2224
+ * Filtering: the JSON sent to the client will only contain the data
2225
+ (fields) defined in the `response_model`. If you returned an object
2226
+ that contains an attribute `password` but the `response_model` does
2227
+ not include that field, the JSON sent to the client would not have
2228
+ that `password`.
2229
+ * Validation: whatever you return will be serialized with the
2230
+ `response_model`, converting any data as necessary to generate the
2231
+ corresponding JSON. But if the data in the object returned is not
2232
+ valid, that would mean a violation of the contract with the client,
2233
+ so it's an error from the API developer. So, FastAPI will raise an
2234
+ error and return a 500 error code (Internal Server Error).
2235
+
2236
+ Read more about it in the
2237
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
2238
+ """
2239
+ ),
2240
+ ] = Default(None),
2241
+ status_code: Annotated[
2242
+ Optional[int],
2243
+ Doc(
2244
+ """
2245
+ The default status code to be used for the response.
2246
+
2247
+ You could override the status code by returning a response directly.
2248
+
2249
+ Read more about it in the
2250
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
2251
+ """
2252
+ ),
2253
+ ] = None,
2254
+ tags: Annotated[
2255
+ Optional[list[Union[str, Enum]]],
2256
+ Doc(
2257
+ """
2258
+ A list of tags to be applied to the *path operation*.
2259
+
2260
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2261
+
2262
+ Read more about it in the
2263
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
2264
+ """
2265
+ ),
2266
+ ] = None,
2267
+ dependencies: Annotated[
2268
+ Optional[Sequence[params.Depends]],
2269
+ Doc(
2270
+ """
2271
+ A list of dependencies (using `Depends()`) to be applied to the
2272
+ *path operation*.
2273
+
2274
+ Read more about it in the
2275
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
2276
+ """
2277
+ ),
2278
+ ] = None,
2279
+ summary: Annotated[
2280
+ Optional[str],
2281
+ Doc(
2282
+ """
2283
+ A summary for the *path operation*.
2284
+
2285
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2286
+
2287
+ Read more about it in the
2288
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2289
+ """
2290
+ ),
2291
+ ] = None,
2292
+ description: Annotated[
2293
+ Optional[str],
2294
+ Doc(
2295
+ """
2296
+ A description for the *path operation*.
2297
+
2298
+ If not provided, it will be extracted automatically from the docstring
2299
+ of the *path operation function*.
2300
+
2301
+ It can contain Markdown.
2302
+
2303
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2304
+
2305
+ Read more about it in the
2306
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2307
+ """
2308
+ ),
2309
+ ] = None,
2310
+ response_description: Annotated[
2311
+ str,
2312
+ Doc(
2313
+ """
2314
+ The description for the default response.
2315
+
2316
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2317
+ """
2318
+ ),
2319
+ ] = "Successful Response",
2320
+ responses: Annotated[
2321
+ Optional[dict[Union[int, str], dict[str, Any]]],
2322
+ Doc(
2323
+ """
2324
+ Additional responses that could be returned by this *path operation*.
2325
+
2326
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2327
+ """
2328
+ ),
2329
+ ] = None,
2330
+ deprecated: Annotated[
2331
+ Optional[bool],
2332
+ Doc(
2333
+ """
2334
+ Mark this *path operation* as deprecated.
2335
+
2336
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2337
+ """
2338
+ ),
2339
+ ] = None,
2340
+ operation_id: Annotated[
2341
+ Optional[str],
2342
+ Doc(
2343
+ """
2344
+ Custom operation ID to be used by this *path operation*.
2345
+
2346
+ By default, it is generated automatically.
2347
+
2348
+ If you provide a custom operation ID, you need to make sure it is
2349
+ unique for the whole API.
2350
+
2351
+ You can customize the
2352
+ operation ID generation with the parameter
2353
+ `generate_unique_id_function` in the `FastAPI` class.
2354
+
2355
+ Read more about it in the
2356
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2357
+ """
2358
+ ),
2359
+ ] = None,
2360
+ response_model_include: Annotated[
2361
+ Optional[IncEx],
2362
+ Doc(
2363
+ """
2364
+ Configuration passed to Pydantic to include only certain fields in the
2365
+ response data.
2366
+
2367
+ Read more about it in the
2368
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2369
+ """
2370
+ ),
2371
+ ] = None,
2372
+ response_model_exclude: Annotated[
2373
+ Optional[IncEx],
2374
+ Doc(
2375
+ """
2376
+ Configuration passed to Pydantic to exclude certain fields in the
2377
+ response data.
2378
+
2379
+ Read more about it in the
2380
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2381
+ """
2382
+ ),
2383
+ ] = None,
2384
+ response_model_by_alias: Annotated[
2385
+ bool,
2386
+ Doc(
2387
+ """
2388
+ Configuration passed to Pydantic to define if the response model
2389
+ should be serialized by alias when an alias is used.
2390
+
2391
+ Read more about it in the
2392
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2393
+ """
2394
+ ),
2395
+ ] = True,
2396
+ response_model_exclude_unset: Annotated[
2397
+ bool,
2398
+ Doc(
2399
+ """
2400
+ Configuration passed to Pydantic to define if the response data
2401
+ should have all the fields, including the ones that were not set and
2402
+ have their default values. This is different from
2403
+ `response_model_exclude_defaults` in that if the fields are set,
2404
+ they will be included in the response, even if the value is the same
2405
+ as the default.
2406
+
2407
+ When `True`, default values are omitted from the response.
2408
+
2409
+ Read more about it in the
2410
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2411
+ """
2412
+ ),
2413
+ ] = False,
2414
+ response_model_exclude_defaults: Annotated[
2415
+ bool,
2416
+ Doc(
2417
+ """
2418
+ Configuration passed to Pydantic to define if the response data
2419
+ should have all the fields, including the ones that have the same value
2420
+ as the default. This is different from `response_model_exclude_unset`
2421
+ in that if the fields are set but contain the same default values,
2422
+ they will be excluded from the response.
2423
+
2424
+ When `True`, default values are omitted from the response.
2425
+
2426
+ Read more about it in the
2427
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2428
+ """
2429
+ ),
2430
+ ] = False,
2431
+ response_model_exclude_none: Annotated[
2432
+ bool,
2433
+ Doc(
2434
+ """
2435
+ Configuration passed to Pydantic to define if the response data should
2436
+ exclude fields set to `None`.
2437
+
2438
+ This is much simpler (less smart) than `response_model_exclude_unset`
2439
+ and `response_model_exclude_defaults`. You probably want to use one of
2440
+ those two instead of this one, as those allow returning `None` values
2441
+ when it makes sense.
2442
+
2443
+ Read more about it in the
2444
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
2445
+ """
2446
+ ),
2447
+ ] = False,
2448
+ include_in_schema: Annotated[
2449
+ bool,
2450
+ Doc(
2451
+ """
2452
+ Include this *path operation* in the generated OpenAPI schema.
2453
+
2454
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
2455
+
2456
+ Read more about it in the
2457
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
2458
+ """
2459
+ ),
2460
+ ] = True,
2461
+ response_class: Annotated[
2462
+ type[Response],
2463
+ Doc(
2464
+ """
2465
+ Response class to be used for this *path operation*.
2466
+
2467
+ This will not be used if you return a response directly.
2468
+
2469
+ Read more about it in the
2470
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
2471
+ """
2472
+ ),
2473
+ ] = Default(JSONResponse),
2474
+ name: Annotated[
2475
+ Optional[str],
2476
+ Doc(
2477
+ """
2478
+ Name for this *path operation*. Only used internally.
2479
+ """
2480
+ ),
2481
+ ] = None,
2482
+ callbacks: Annotated[
2483
+ Optional[list[BaseRoute]],
2484
+ Doc(
2485
+ """
2486
+ List of *path operations* that will be used as OpenAPI callbacks.
2487
+
2488
+ This is only for OpenAPI documentation, the callbacks won't be used
2489
+ directly.
2490
+
2491
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2492
+
2493
+ Read more about it in the
2494
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
2495
+ """
2496
+ ),
2497
+ ] = None,
2498
+ openapi_extra: Annotated[
2499
+ Optional[dict[str, Any]],
2500
+ Doc(
2501
+ """
2502
+ Extra metadata to be included in the OpenAPI schema for this *path
2503
+ operation*.
2504
+
2505
+ Read more about it in the
2506
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
2507
+ """
2508
+ ),
2509
+ ] = None,
2510
+ generate_unique_id_function: Annotated[
2511
+ Callable[[APIRoute], str],
2512
+ Doc(
2513
+ """
2514
+ Customize the function used to generate unique IDs for the *path
2515
+ operations* shown in the generated OpenAPI.
2516
+
2517
+ This is particularly useful when automatically generating clients or
2518
+ SDKs for your API.
2519
+
2520
+ Read more about it in the
2521
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2522
+ """
2523
+ ),
2524
+ ] = Default(generate_unique_id),
2525
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
2526
+ """
2527
+ Add a *path operation* using an HTTP POST operation.
2528
+
2529
+ ## Example
2530
+
2531
+ ```python
2532
+ from fastapi import APIRouter, FastAPI
2533
+ from pydantic import BaseModel
2534
+
2535
+ class Item(BaseModel):
2536
+ name: str
2537
+ description: str | None = None
2538
+
2539
+ app = FastAPI()
2540
+ router = APIRouter()
2541
+
2542
+ @router.post("/items/")
2543
+ def create_item(item: Item):
2544
+ return {"message": "Item created"}
2545
+
2546
+ app.include_router(router)
2547
+ ```
2548
+ """
2549
+ return self.api_route(
2550
+ path=path,
2551
+ response_model=response_model,
2552
+ status_code=status_code,
2553
+ tags=tags,
2554
+ dependencies=dependencies,
2555
+ summary=summary,
2556
+ description=description,
2557
+ response_description=response_description,
2558
+ responses=responses,
2559
+ deprecated=deprecated,
2560
+ methods=["POST"],
2561
+ operation_id=operation_id,
2562
+ response_model_include=response_model_include,
2563
+ response_model_exclude=response_model_exclude,
2564
+ response_model_by_alias=response_model_by_alias,
2565
+ response_model_exclude_unset=response_model_exclude_unset,
2566
+ response_model_exclude_defaults=response_model_exclude_defaults,
2567
+ response_model_exclude_none=response_model_exclude_none,
2568
+ include_in_schema=include_in_schema,
2569
+ response_class=response_class,
2570
+ name=name,
2571
+ callbacks=callbacks,
2572
+ openapi_extra=openapi_extra,
2573
+ generate_unique_id_function=generate_unique_id_function,
2574
+ )
2575
+
2576
+ def delete(
2577
+ self,
2578
+ path: Annotated[
2579
+ str,
2580
+ Doc(
2581
+ """
2582
+ The URL path to be used for this *path operation*.
2583
+
2584
+ For example, in `http://example.com/items`, the path is `/items`.
2585
+ """
2586
+ ),
2587
+ ],
2588
+ *,
2589
+ response_model: Annotated[
2590
+ Any,
2591
+ Doc(
2592
+ """
2593
+ The type to use for the response.
2594
+
2595
+ It could be any valid Pydantic *field* type. So, it doesn't have to
2596
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
2597
+ etc.
2598
+
2599
+ It will be used for:
2600
+
2601
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
2602
+ show it as the response (JSON Schema).
2603
+ * Serialization: you could return an arbitrary object and the
2604
+ `response_model` would be used to serialize that object into the
2605
+ corresponding JSON.
2606
+ * Filtering: the JSON sent to the client will only contain the data
2607
+ (fields) defined in the `response_model`. If you returned an object
2608
+ that contains an attribute `password` but the `response_model` does
2609
+ not include that field, the JSON sent to the client would not have
2610
+ that `password`.
2611
+ * Validation: whatever you return will be serialized with the
2612
+ `response_model`, converting any data as necessary to generate the
2613
+ corresponding JSON. But if the data in the object returned is not
2614
+ valid, that would mean a violation of the contract with the client,
2615
+ so it's an error from the API developer. So, FastAPI will raise an
2616
+ error and return a 500 error code (Internal Server Error).
2617
+
2618
+ Read more about it in the
2619
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
2620
+ """
2621
+ ),
2622
+ ] = Default(None),
2623
+ status_code: Annotated[
2624
+ Optional[int],
2625
+ Doc(
2626
+ """
2627
+ The default status code to be used for the response.
2628
+
2629
+ You could override the status code by returning a response directly.
2630
+
2631
+ Read more about it in the
2632
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
2633
+ """
2634
+ ),
2635
+ ] = None,
2636
+ tags: Annotated[
2637
+ Optional[list[Union[str, Enum]]],
2638
+ Doc(
2639
+ """
2640
+ A list of tags to be applied to the *path operation*.
2641
+
2642
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2643
+
2644
+ Read more about it in the
2645
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
2646
+ """
2647
+ ),
2648
+ ] = None,
2649
+ dependencies: Annotated[
2650
+ Optional[Sequence[params.Depends]],
2651
+ Doc(
2652
+ """
2653
+ A list of dependencies (using `Depends()`) to be applied to the
2654
+ *path operation*.
2655
+
2656
+ Read more about it in the
2657
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
2658
+ """
2659
+ ),
2660
+ ] = None,
2661
+ summary: Annotated[
2662
+ Optional[str],
2663
+ Doc(
2664
+ """
2665
+ A summary for the *path operation*.
2666
+
2667
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2668
+
2669
+ Read more about it in the
2670
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2671
+ """
2672
+ ),
2673
+ ] = None,
2674
+ description: Annotated[
2675
+ Optional[str],
2676
+ Doc(
2677
+ """
2678
+ A description for the *path operation*.
2679
+
2680
+ If not provided, it will be extracted automatically from the docstring
2681
+ of the *path operation function*.
2682
+
2683
+ It can contain Markdown.
2684
+
2685
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2686
+
2687
+ Read more about it in the
2688
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2689
+ """
2690
+ ),
2691
+ ] = None,
2692
+ response_description: Annotated[
2693
+ str,
2694
+ Doc(
2695
+ """
2696
+ The description for the default response.
2697
+
2698
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2699
+ """
2700
+ ),
2701
+ ] = "Successful Response",
2702
+ responses: Annotated[
2703
+ Optional[dict[Union[int, str], dict[str, Any]]],
2704
+ Doc(
2705
+ """
2706
+ Additional responses that could be returned by this *path operation*.
2707
+
2708
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2709
+ """
2710
+ ),
2711
+ ] = None,
2712
+ deprecated: Annotated[
2713
+ Optional[bool],
2714
+ Doc(
2715
+ """
2716
+ Mark this *path operation* as deprecated.
2717
+
2718
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2719
+ """
2720
+ ),
2721
+ ] = None,
2722
+ operation_id: Annotated[
2723
+ Optional[str],
2724
+ Doc(
2725
+ """
2726
+ Custom operation ID to be used by this *path operation*.
2727
+
2728
+ By default, it is generated automatically.
2729
+
2730
+ If you provide a custom operation ID, you need to make sure it is
2731
+ unique for the whole API.
2732
+
2733
+ You can customize the
2734
+ operation ID generation with the parameter
2735
+ `generate_unique_id_function` in the `FastAPI` class.
2736
+
2737
+ Read more about it in the
2738
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2739
+ """
2740
+ ),
2741
+ ] = None,
2742
+ response_model_include: Annotated[
2743
+ Optional[IncEx],
2744
+ Doc(
2745
+ """
2746
+ Configuration passed to Pydantic to include only certain fields in the
2747
+ response data.
2748
+
2749
+ Read more about it in the
2750
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2751
+ """
2752
+ ),
2753
+ ] = None,
2754
+ response_model_exclude: Annotated[
2755
+ Optional[IncEx],
2756
+ Doc(
2757
+ """
2758
+ Configuration passed to Pydantic to exclude certain fields in the
2759
+ response data.
2760
+
2761
+ Read more about it in the
2762
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2763
+ """
2764
+ ),
2765
+ ] = None,
2766
+ response_model_by_alias: Annotated[
2767
+ bool,
2768
+ Doc(
2769
+ """
2770
+ Configuration passed to Pydantic to define if the response model
2771
+ should be serialized by alias when an alias is used.
2772
+
2773
+ Read more about it in the
2774
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2775
+ """
2776
+ ),
2777
+ ] = True,
2778
+ response_model_exclude_unset: Annotated[
2779
+ bool,
2780
+ Doc(
2781
+ """
2782
+ Configuration passed to Pydantic to define if the response data
2783
+ should have all the fields, including the ones that were not set and
2784
+ have their default values. This is different from
2785
+ `response_model_exclude_defaults` in that if the fields are set,
2786
+ they will be included in the response, even if the value is the same
2787
+ as the default.
2788
+
2789
+ When `True`, default values are omitted from the response.
2790
+
2791
+ Read more about it in the
2792
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2793
+ """
2794
+ ),
2795
+ ] = False,
2796
+ response_model_exclude_defaults: Annotated[
2797
+ bool,
2798
+ Doc(
2799
+ """
2800
+ Configuration passed to Pydantic to define if the response data
2801
+ should have all the fields, including the ones that have the same value
2802
+ as the default. This is different from `response_model_exclude_unset`
2803
+ in that if the fields are set but contain the same default values,
2804
+ they will be excluded from the response.
2805
+
2806
+ When `True`, default values are omitted from the response.
2807
+
2808
+ Read more about it in the
2809
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2810
+ """
2811
+ ),
2812
+ ] = False,
2813
+ response_model_exclude_none: Annotated[
2814
+ bool,
2815
+ Doc(
2816
+ """
2817
+ Configuration passed to Pydantic to define if the response data should
2818
+ exclude fields set to `None`.
2819
+
2820
+ This is much simpler (less smart) than `response_model_exclude_unset`
2821
+ and `response_model_exclude_defaults`. You probably want to use one of
2822
+ those two instead of this one, as those allow returning `None` values
2823
+ when it makes sense.
2824
+
2825
+ Read more about it in the
2826
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
2827
+ """
2828
+ ),
2829
+ ] = False,
2830
+ include_in_schema: Annotated[
2831
+ bool,
2832
+ Doc(
2833
+ """
2834
+ Include this *path operation* in the generated OpenAPI schema.
2835
+
2836
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
2837
+
2838
+ Read more about it in the
2839
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
2840
+ """
2841
+ ),
2842
+ ] = True,
2843
+ response_class: Annotated[
2844
+ type[Response],
2845
+ Doc(
2846
+ """
2847
+ Response class to be used for this *path operation*.
2848
+
2849
+ This will not be used if you return a response directly.
2850
+
2851
+ Read more about it in the
2852
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
2853
+ """
2854
+ ),
2855
+ ] = Default(JSONResponse),
2856
+ name: Annotated[
2857
+ Optional[str],
2858
+ Doc(
2859
+ """
2860
+ Name for this *path operation*. Only used internally.
2861
+ """
2862
+ ),
2863
+ ] = None,
2864
+ callbacks: Annotated[
2865
+ Optional[list[BaseRoute]],
2866
+ Doc(
2867
+ """
2868
+ List of *path operations* that will be used as OpenAPI callbacks.
2869
+
2870
+ This is only for OpenAPI documentation, the callbacks won't be used
2871
+ directly.
2872
+
2873
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2874
+
2875
+ Read more about it in the
2876
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
2877
+ """
2878
+ ),
2879
+ ] = None,
2880
+ openapi_extra: Annotated[
2881
+ Optional[dict[str, Any]],
2882
+ Doc(
2883
+ """
2884
+ Extra metadata to be included in the OpenAPI schema for this *path
2885
+ operation*.
2886
+
2887
+ Read more about it in the
2888
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
2889
+ """
2890
+ ),
2891
+ ] = None,
2892
+ generate_unique_id_function: Annotated[
2893
+ Callable[[APIRoute], str],
2894
+ Doc(
2895
+ """
2896
+ Customize the function used to generate unique IDs for the *path
2897
+ operations* shown in the generated OpenAPI.
2898
+
2899
+ This is particularly useful when automatically generating clients or
2900
+ SDKs for your API.
2901
+
2902
+ Read more about it in the
2903
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2904
+ """
2905
+ ),
2906
+ ] = Default(generate_unique_id),
2907
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
2908
+ """
2909
+ Add a *path operation* using an HTTP DELETE operation.
2910
+
2911
+ ## Example
2912
+
2913
+ ```python
2914
+ from fastapi import APIRouter, FastAPI
2915
+
2916
+ app = FastAPI()
2917
+ router = APIRouter()
2918
+
2919
+ @router.delete("/items/{item_id}")
2920
+ def delete_item(item_id: str):
2921
+ return {"message": "Item deleted"}
2922
+
2923
+ app.include_router(router)
2924
+ ```
2925
+ """
2926
+ return self.api_route(
2927
+ path=path,
2928
+ response_model=response_model,
2929
+ status_code=status_code,
2930
+ tags=tags,
2931
+ dependencies=dependencies,
2932
+ summary=summary,
2933
+ description=description,
2934
+ response_description=response_description,
2935
+ responses=responses,
2936
+ deprecated=deprecated,
2937
+ methods=["DELETE"],
2938
+ operation_id=operation_id,
2939
+ response_model_include=response_model_include,
2940
+ response_model_exclude=response_model_exclude,
2941
+ response_model_by_alias=response_model_by_alias,
2942
+ response_model_exclude_unset=response_model_exclude_unset,
2943
+ response_model_exclude_defaults=response_model_exclude_defaults,
2944
+ response_model_exclude_none=response_model_exclude_none,
2945
+ include_in_schema=include_in_schema,
2946
+ response_class=response_class,
2947
+ name=name,
2948
+ callbacks=callbacks,
2949
+ openapi_extra=openapi_extra,
2950
+ generate_unique_id_function=generate_unique_id_function,
2951
+ )
2952
+
2953
+ def options(
2954
+ self,
2955
+ path: Annotated[
2956
+ str,
2957
+ Doc(
2958
+ """
2959
+ The URL path to be used for this *path operation*.
2960
+
2961
+ For example, in `http://example.com/items`, the path is `/items`.
2962
+ """
2963
+ ),
2964
+ ],
2965
+ *,
2966
+ response_model: Annotated[
2967
+ Any,
2968
+ Doc(
2969
+ """
2970
+ The type to use for the response.
2971
+
2972
+ It could be any valid Pydantic *field* type. So, it doesn't have to
2973
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
2974
+ etc.
2975
+
2976
+ It will be used for:
2977
+
2978
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
2979
+ show it as the response (JSON Schema).
2980
+ * Serialization: you could return an arbitrary object and the
2981
+ `response_model` would be used to serialize that object into the
2982
+ corresponding JSON.
2983
+ * Filtering: the JSON sent to the client will only contain the data
2984
+ (fields) defined in the `response_model`. If you returned an object
2985
+ that contains an attribute `password` but the `response_model` does
2986
+ not include that field, the JSON sent to the client would not have
2987
+ that `password`.
2988
+ * Validation: whatever you return will be serialized with the
2989
+ `response_model`, converting any data as necessary to generate the
2990
+ corresponding JSON. But if the data in the object returned is not
2991
+ valid, that would mean a violation of the contract with the client,
2992
+ so it's an error from the API developer. So, FastAPI will raise an
2993
+ error and return a 500 error code (Internal Server Error).
2994
+
2995
+ Read more about it in the
2996
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
2997
+ """
2998
+ ),
2999
+ ] = Default(None),
3000
+ status_code: Annotated[
3001
+ Optional[int],
3002
+ Doc(
3003
+ """
3004
+ The default status code to be used for the response.
3005
+
3006
+ You could override the status code by returning a response directly.
3007
+
3008
+ Read more about it in the
3009
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
3010
+ """
3011
+ ),
3012
+ ] = None,
3013
+ tags: Annotated[
3014
+ Optional[list[Union[str, Enum]]],
3015
+ Doc(
3016
+ """
3017
+ A list of tags to be applied to the *path operation*.
3018
+
3019
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3020
+
3021
+ Read more about it in the
3022
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
3023
+ """
3024
+ ),
3025
+ ] = None,
3026
+ dependencies: Annotated[
3027
+ Optional[Sequence[params.Depends]],
3028
+ Doc(
3029
+ """
3030
+ A list of dependencies (using `Depends()`) to be applied to the
3031
+ *path operation*.
3032
+
3033
+ Read more about it in the
3034
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
3035
+ """
3036
+ ),
3037
+ ] = None,
3038
+ summary: Annotated[
3039
+ Optional[str],
3040
+ Doc(
3041
+ """
3042
+ A summary for the *path operation*.
3043
+
3044
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3045
+
3046
+ Read more about it in the
3047
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3048
+ """
3049
+ ),
3050
+ ] = None,
3051
+ description: Annotated[
3052
+ Optional[str],
3053
+ Doc(
3054
+ """
3055
+ A description for the *path operation*.
3056
+
3057
+ If not provided, it will be extracted automatically from the docstring
3058
+ of the *path operation function*.
3059
+
3060
+ It can contain Markdown.
3061
+
3062
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3063
+
3064
+ Read more about it in the
3065
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3066
+ """
3067
+ ),
3068
+ ] = None,
3069
+ response_description: Annotated[
3070
+ str,
3071
+ Doc(
3072
+ """
3073
+ The description for the default response.
3074
+
3075
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3076
+ """
3077
+ ),
3078
+ ] = "Successful Response",
3079
+ responses: Annotated[
3080
+ Optional[dict[Union[int, str], dict[str, Any]]],
3081
+ Doc(
3082
+ """
3083
+ Additional responses that could be returned by this *path operation*.
3084
+
3085
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3086
+ """
3087
+ ),
3088
+ ] = None,
3089
+ deprecated: Annotated[
3090
+ Optional[bool],
3091
+ Doc(
3092
+ """
3093
+ Mark this *path operation* as deprecated.
3094
+
3095
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3096
+ """
3097
+ ),
3098
+ ] = None,
3099
+ operation_id: Annotated[
3100
+ Optional[str],
3101
+ Doc(
3102
+ """
3103
+ Custom operation ID to be used by this *path operation*.
3104
+
3105
+ By default, it is generated automatically.
3106
+
3107
+ If you provide a custom operation ID, you need to make sure it is
3108
+ unique for the whole API.
3109
+
3110
+ You can customize the
3111
+ operation ID generation with the parameter
3112
+ `generate_unique_id_function` in the `FastAPI` class.
3113
+
3114
+ Read more about it in the
3115
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3116
+ """
3117
+ ),
3118
+ ] = None,
3119
+ response_model_include: Annotated[
3120
+ Optional[IncEx],
3121
+ Doc(
3122
+ """
3123
+ Configuration passed to Pydantic to include only certain fields in the
3124
+ response data.
3125
+
3126
+ Read more about it in the
3127
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3128
+ """
3129
+ ),
3130
+ ] = None,
3131
+ response_model_exclude: Annotated[
3132
+ Optional[IncEx],
3133
+ Doc(
3134
+ """
3135
+ Configuration passed to Pydantic to exclude certain fields in the
3136
+ response data.
3137
+
3138
+ Read more about it in the
3139
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3140
+ """
3141
+ ),
3142
+ ] = None,
3143
+ response_model_by_alias: Annotated[
3144
+ bool,
3145
+ Doc(
3146
+ """
3147
+ Configuration passed to Pydantic to define if the response model
3148
+ should be serialized by alias when an alias is used.
3149
+
3150
+ Read more about it in the
3151
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3152
+ """
3153
+ ),
3154
+ ] = True,
3155
+ response_model_exclude_unset: Annotated[
3156
+ bool,
3157
+ Doc(
3158
+ """
3159
+ Configuration passed to Pydantic to define if the response data
3160
+ should have all the fields, including the ones that were not set and
3161
+ have their default values. This is different from
3162
+ `response_model_exclude_defaults` in that if the fields are set,
3163
+ they will be included in the response, even if the value is the same
3164
+ as the default.
3165
+
3166
+ When `True`, default values are omitted from the response.
3167
+
3168
+ Read more about it in the
3169
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3170
+ """
3171
+ ),
3172
+ ] = False,
3173
+ response_model_exclude_defaults: Annotated[
3174
+ bool,
3175
+ Doc(
3176
+ """
3177
+ Configuration passed to Pydantic to define if the response data
3178
+ should have all the fields, including the ones that have the same value
3179
+ as the default. This is different from `response_model_exclude_unset`
3180
+ in that if the fields are set but contain the same default values,
3181
+ they will be excluded from the response.
3182
+
3183
+ When `True`, default values are omitted from the response.
3184
+
3185
+ Read more about it in the
3186
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3187
+ """
3188
+ ),
3189
+ ] = False,
3190
+ response_model_exclude_none: Annotated[
3191
+ bool,
3192
+ Doc(
3193
+ """
3194
+ Configuration passed to Pydantic to define if the response data should
3195
+ exclude fields set to `None`.
3196
+
3197
+ This is much simpler (less smart) than `response_model_exclude_unset`
3198
+ and `response_model_exclude_defaults`. You probably want to use one of
3199
+ those two instead of this one, as those allow returning `None` values
3200
+ when it makes sense.
3201
+
3202
+ Read more about it in the
3203
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
3204
+ """
3205
+ ),
3206
+ ] = False,
3207
+ include_in_schema: Annotated[
3208
+ bool,
3209
+ Doc(
3210
+ """
3211
+ Include this *path operation* in the generated OpenAPI schema.
3212
+
3213
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
3214
+
3215
+ Read more about it in the
3216
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
3217
+ """
3218
+ ),
3219
+ ] = True,
3220
+ response_class: Annotated[
3221
+ type[Response],
3222
+ Doc(
3223
+ """
3224
+ Response class to be used for this *path operation*.
3225
+
3226
+ This will not be used if you return a response directly.
3227
+
3228
+ Read more about it in the
3229
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
3230
+ """
3231
+ ),
3232
+ ] = Default(JSONResponse),
3233
+ name: Annotated[
3234
+ Optional[str],
3235
+ Doc(
3236
+ """
3237
+ Name for this *path operation*. Only used internally.
3238
+ """
3239
+ ),
3240
+ ] = None,
3241
+ callbacks: Annotated[
3242
+ Optional[list[BaseRoute]],
3243
+ Doc(
3244
+ """
3245
+ List of *path operations* that will be used as OpenAPI callbacks.
3246
+
3247
+ This is only for OpenAPI documentation, the callbacks won't be used
3248
+ directly.
3249
+
3250
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3251
+
3252
+ Read more about it in the
3253
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
3254
+ """
3255
+ ),
3256
+ ] = None,
3257
+ openapi_extra: Annotated[
3258
+ Optional[dict[str, Any]],
3259
+ Doc(
3260
+ """
3261
+ Extra metadata to be included in the OpenAPI schema for this *path
3262
+ operation*.
3263
+
3264
+ Read more about it in the
3265
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
3266
+ """
3267
+ ),
3268
+ ] = None,
3269
+ generate_unique_id_function: Annotated[
3270
+ Callable[[APIRoute], str],
3271
+ Doc(
3272
+ """
3273
+ Customize the function used to generate unique IDs for the *path
3274
+ operations* shown in the generated OpenAPI.
3275
+
3276
+ This is particularly useful when automatically generating clients or
3277
+ SDKs for your API.
3278
+
3279
+ Read more about it in the
3280
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3281
+ """
3282
+ ),
3283
+ ] = Default(generate_unique_id),
3284
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
3285
+ """
3286
+ Add a *path operation* using an HTTP OPTIONS operation.
3287
+
3288
+ ## Example
3289
+
3290
+ ```python
3291
+ from fastapi import APIRouter, FastAPI
3292
+
3293
+ app = FastAPI()
3294
+ router = APIRouter()
3295
+
3296
+ @router.options("/items/")
3297
+ def get_item_options():
3298
+ return {"additions": ["Aji", "Guacamole"]}
3299
+
3300
+ app.include_router(router)
3301
+ ```
3302
+ """
3303
+ return self.api_route(
3304
+ path=path,
3305
+ response_model=response_model,
3306
+ status_code=status_code,
3307
+ tags=tags,
3308
+ dependencies=dependencies,
3309
+ summary=summary,
3310
+ description=description,
3311
+ response_description=response_description,
3312
+ responses=responses,
3313
+ deprecated=deprecated,
3314
+ methods=["OPTIONS"],
3315
+ operation_id=operation_id,
3316
+ response_model_include=response_model_include,
3317
+ response_model_exclude=response_model_exclude,
3318
+ response_model_by_alias=response_model_by_alias,
3319
+ response_model_exclude_unset=response_model_exclude_unset,
3320
+ response_model_exclude_defaults=response_model_exclude_defaults,
3321
+ response_model_exclude_none=response_model_exclude_none,
3322
+ include_in_schema=include_in_schema,
3323
+ response_class=response_class,
3324
+ name=name,
3325
+ callbacks=callbacks,
3326
+ openapi_extra=openapi_extra,
3327
+ generate_unique_id_function=generate_unique_id_function,
3328
+ )
3329
+
3330
+ def head(
3331
+ self,
3332
+ path: Annotated[
3333
+ str,
3334
+ Doc(
3335
+ """
3336
+ The URL path to be used for this *path operation*.
3337
+
3338
+ For example, in `http://example.com/items`, the path is `/items`.
3339
+ """
3340
+ ),
3341
+ ],
3342
+ *,
3343
+ response_model: Annotated[
3344
+ Any,
3345
+ Doc(
3346
+ """
3347
+ The type to use for the response.
3348
+
3349
+ It could be any valid Pydantic *field* type. So, it doesn't have to
3350
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
3351
+ etc.
3352
+
3353
+ It will be used for:
3354
+
3355
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
3356
+ show it as the response (JSON Schema).
3357
+ * Serialization: you could return an arbitrary object and the
3358
+ `response_model` would be used to serialize that object into the
3359
+ corresponding JSON.
3360
+ * Filtering: the JSON sent to the client will only contain the data
3361
+ (fields) defined in the `response_model`. If you returned an object
3362
+ that contains an attribute `password` but the `response_model` does
3363
+ not include that field, the JSON sent to the client would not have
3364
+ that `password`.
3365
+ * Validation: whatever you return will be serialized with the
3366
+ `response_model`, converting any data as necessary to generate the
3367
+ corresponding JSON. But if the data in the object returned is not
3368
+ valid, that would mean a violation of the contract with the client,
3369
+ so it's an error from the API developer. So, FastAPI will raise an
3370
+ error and return a 500 error code (Internal Server Error).
3371
+
3372
+ Read more about it in the
3373
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
3374
+ """
3375
+ ),
3376
+ ] = Default(None),
3377
+ status_code: Annotated[
3378
+ Optional[int],
3379
+ Doc(
3380
+ """
3381
+ The default status code to be used for the response.
3382
+
3383
+ You could override the status code by returning a response directly.
3384
+
3385
+ Read more about it in the
3386
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
3387
+ """
3388
+ ),
3389
+ ] = None,
3390
+ tags: Annotated[
3391
+ Optional[list[Union[str, Enum]]],
3392
+ Doc(
3393
+ """
3394
+ A list of tags to be applied to the *path operation*.
3395
+
3396
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3397
+
3398
+ Read more about it in the
3399
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
3400
+ """
3401
+ ),
3402
+ ] = None,
3403
+ dependencies: Annotated[
3404
+ Optional[Sequence[params.Depends]],
3405
+ Doc(
3406
+ """
3407
+ A list of dependencies (using `Depends()`) to be applied to the
3408
+ *path operation*.
3409
+
3410
+ Read more about it in the
3411
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
3412
+ """
3413
+ ),
3414
+ ] = None,
3415
+ summary: Annotated[
3416
+ Optional[str],
3417
+ Doc(
3418
+ """
3419
+ A summary for the *path operation*.
3420
+
3421
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3422
+
3423
+ Read more about it in the
3424
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3425
+ """
3426
+ ),
3427
+ ] = None,
3428
+ description: Annotated[
3429
+ Optional[str],
3430
+ Doc(
3431
+ """
3432
+ A description for the *path operation*.
3433
+
3434
+ If not provided, it will be extracted automatically from the docstring
3435
+ of the *path operation function*.
3436
+
3437
+ It can contain Markdown.
3438
+
3439
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3440
+
3441
+ Read more about it in the
3442
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3443
+ """
3444
+ ),
3445
+ ] = None,
3446
+ response_description: Annotated[
3447
+ str,
3448
+ Doc(
3449
+ """
3450
+ The description for the default response.
3451
+
3452
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3453
+ """
3454
+ ),
3455
+ ] = "Successful Response",
3456
+ responses: Annotated[
3457
+ Optional[dict[Union[int, str], dict[str, Any]]],
3458
+ Doc(
3459
+ """
3460
+ Additional responses that could be returned by this *path operation*.
3461
+
3462
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3463
+ """
3464
+ ),
3465
+ ] = None,
3466
+ deprecated: Annotated[
3467
+ Optional[bool],
3468
+ Doc(
3469
+ """
3470
+ Mark this *path operation* as deprecated.
3471
+
3472
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3473
+ """
3474
+ ),
3475
+ ] = None,
3476
+ operation_id: Annotated[
3477
+ Optional[str],
3478
+ Doc(
3479
+ """
3480
+ Custom operation ID to be used by this *path operation*.
3481
+
3482
+ By default, it is generated automatically.
3483
+
3484
+ If you provide a custom operation ID, you need to make sure it is
3485
+ unique for the whole API.
3486
+
3487
+ You can customize the
3488
+ operation ID generation with the parameter
3489
+ `generate_unique_id_function` in the `FastAPI` class.
3490
+
3491
+ Read more about it in the
3492
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3493
+ """
3494
+ ),
3495
+ ] = None,
3496
+ response_model_include: Annotated[
3497
+ Optional[IncEx],
3498
+ Doc(
3499
+ """
3500
+ Configuration passed to Pydantic to include only certain fields in the
3501
+ response data.
3502
+
3503
+ Read more about it in the
3504
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3505
+ """
3506
+ ),
3507
+ ] = None,
3508
+ response_model_exclude: Annotated[
3509
+ Optional[IncEx],
3510
+ Doc(
3511
+ """
3512
+ Configuration passed to Pydantic to exclude certain fields in the
3513
+ response data.
3514
+
3515
+ Read more about it in the
3516
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3517
+ """
3518
+ ),
3519
+ ] = None,
3520
+ response_model_by_alias: Annotated[
3521
+ bool,
3522
+ Doc(
3523
+ """
3524
+ Configuration passed to Pydantic to define if the response model
3525
+ should be serialized by alias when an alias is used.
3526
+
3527
+ Read more about it in the
3528
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3529
+ """
3530
+ ),
3531
+ ] = True,
3532
+ response_model_exclude_unset: Annotated[
3533
+ bool,
3534
+ Doc(
3535
+ """
3536
+ Configuration passed to Pydantic to define if the response data
3537
+ should have all the fields, including the ones that were not set and
3538
+ have their default values. This is different from
3539
+ `response_model_exclude_defaults` in that if the fields are set,
3540
+ they will be included in the response, even if the value is the same
3541
+ as the default.
3542
+
3543
+ When `True`, default values are omitted from the response.
3544
+
3545
+ Read more about it in the
3546
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3547
+ """
3548
+ ),
3549
+ ] = False,
3550
+ response_model_exclude_defaults: Annotated[
3551
+ bool,
3552
+ Doc(
3553
+ """
3554
+ Configuration passed to Pydantic to define if the response data
3555
+ should have all the fields, including the ones that have the same value
3556
+ as the default. This is different from `response_model_exclude_unset`
3557
+ in that if the fields are set but contain the same default values,
3558
+ they will be excluded from the response.
3559
+
3560
+ When `True`, default values are omitted from the response.
3561
+
3562
+ Read more about it in the
3563
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3564
+ """
3565
+ ),
3566
+ ] = False,
3567
+ response_model_exclude_none: Annotated[
3568
+ bool,
3569
+ Doc(
3570
+ """
3571
+ Configuration passed to Pydantic to define if the response data should
3572
+ exclude fields set to `None`.
3573
+
3574
+ This is much simpler (less smart) than `response_model_exclude_unset`
3575
+ and `response_model_exclude_defaults`. You probably want to use one of
3576
+ those two instead of this one, as those allow returning `None` values
3577
+ when it makes sense.
3578
+
3579
+ Read more about it in the
3580
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
3581
+ """
3582
+ ),
3583
+ ] = False,
3584
+ include_in_schema: Annotated[
3585
+ bool,
3586
+ Doc(
3587
+ """
3588
+ Include this *path operation* in the generated OpenAPI schema.
3589
+
3590
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
3591
+
3592
+ Read more about it in the
3593
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
3594
+ """
3595
+ ),
3596
+ ] = True,
3597
+ response_class: Annotated[
3598
+ type[Response],
3599
+ Doc(
3600
+ """
3601
+ Response class to be used for this *path operation*.
3602
+
3603
+ This will not be used if you return a response directly.
3604
+
3605
+ Read more about it in the
3606
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
3607
+ """
3608
+ ),
3609
+ ] = Default(JSONResponse),
3610
+ name: Annotated[
3611
+ Optional[str],
3612
+ Doc(
3613
+ """
3614
+ Name for this *path operation*. Only used internally.
3615
+ """
3616
+ ),
3617
+ ] = None,
3618
+ callbacks: Annotated[
3619
+ Optional[list[BaseRoute]],
3620
+ Doc(
3621
+ """
3622
+ List of *path operations* that will be used as OpenAPI callbacks.
3623
+
3624
+ This is only for OpenAPI documentation, the callbacks won't be used
3625
+ directly.
3626
+
3627
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3628
+
3629
+ Read more about it in the
3630
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
3631
+ """
3632
+ ),
3633
+ ] = None,
3634
+ openapi_extra: Annotated[
3635
+ Optional[dict[str, Any]],
3636
+ Doc(
3637
+ """
3638
+ Extra metadata to be included in the OpenAPI schema for this *path
3639
+ operation*.
3640
+
3641
+ Read more about it in the
3642
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
3643
+ """
3644
+ ),
3645
+ ] = None,
3646
+ generate_unique_id_function: Annotated[
3647
+ Callable[[APIRoute], str],
3648
+ Doc(
3649
+ """
3650
+ Customize the function used to generate unique IDs for the *path
3651
+ operations* shown in the generated OpenAPI.
3652
+
3653
+ This is particularly useful when automatically generating clients or
3654
+ SDKs for your API.
3655
+
3656
+ Read more about it in the
3657
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3658
+ """
3659
+ ),
3660
+ ] = Default(generate_unique_id),
3661
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
3662
+ """
3663
+ Add a *path operation* using an HTTP HEAD operation.
3664
+
3665
+ ## Example
3666
+
3667
+ ```python
3668
+ from fastapi import APIRouter, FastAPI
3669
+ from pydantic import BaseModel
3670
+
3671
+ class Item(BaseModel):
3672
+ name: str
3673
+ description: str | None = None
3674
+
3675
+ app = FastAPI()
3676
+ router = APIRouter()
3677
+
3678
+ @router.head("/items/", status_code=204)
3679
+ def get_items_headers(response: Response):
3680
+ response.headers["X-Cat-Dog"] = "Alone in the world"
3681
+
3682
+ app.include_router(router)
3683
+ ```
3684
+ """
3685
+ return self.api_route(
3686
+ path=path,
3687
+ response_model=response_model,
3688
+ status_code=status_code,
3689
+ tags=tags,
3690
+ dependencies=dependencies,
3691
+ summary=summary,
3692
+ description=description,
3693
+ response_description=response_description,
3694
+ responses=responses,
3695
+ deprecated=deprecated,
3696
+ methods=["HEAD"],
3697
+ operation_id=operation_id,
3698
+ response_model_include=response_model_include,
3699
+ response_model_exclude=response_model_exclude,
3700
+ response_model_by_alias=response_model_by_alias,
3701
+ response_model_exclude_unset=response_model_exclude_unset,
3702
+ response_model_exclude_defaults=response_model_exclude_defaults,
3703
+ response_model_exclude_none=response_model_exclude_none,
3704
+ include_in_schema=include_in_schema,
3705
+ response_class=response_class,
3706
+ name=name,
3707
+ callbacks=callbacks,
3708
+ openapi_extra=openapi_extra,
3709
+ generate_unique_id_function=generate_unique_id_function,
3710
+ )
3711
+
3712
+ def patch(
3713
+ self,
3714
+ path: Annotated[
3715
+ str,
3716
+ Doc(
3717
+ """
3718
+ The URL path to be used for this *path operation*.
3719
+
3720
+ For example, in `http://example.com/items`, the path is `/items`.
3721
+ """
3722
+ ),
3723
+ ],
3724
+ *,
3725
+ response_model: Annotated[
3726
+ Any,
3727
+ Doc(
3728
+ """
3729
+ The type to use for the response.
3730
+
3731
+ It could be any valid Pydantic *field* type. So, it doesn't have to
3732
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
3733
+ etc.
3734
+
3735
+ It will be used for:
3736
+
3737
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
3738
+ show it as the response (JSON Schema).
3739
+ * Serialization: you could return an arbitrary object and the
3740
+ `response_model` would be used to serialize that object into the
3741
+ corresponding JSON.
3742
+ * Filtering: the JSON sent to the client will only contain the data
3743
+ (fields) defined in the `response_model`. If you returned an object
3744
+ that contains an attribute `password` but the `response_model` does
3745
+ not include that field, the JSON sent to the client would not have
3746
+ that `password`.
3747
+ * Validation: whatever you return will be serialized with the
3748
+ `response_model`, converting any data as necessary to generate the
3749
+ corresponding JSON. But if the data in the object returned is not
3750
+ valid, that would mean a violation of the contract with the client,
3751
+ so it's an error from the API developer. So, FastAPI will raise an
3752
+ error and return a 500 error code (Internal Server Error).
3753
+
3754
+ Read more about it in the
3755
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
3756
+ """
3757
+ ),
3758
+ ] = Default(None),
3759
+ status_code: Annotated[
3760
+ Optional[int],
3761
+ Doc(
3762
+ """
3763
+ The default status code to be used for the response.
3764
+
3765
+ You could override the status code by returning a response directly.
3766
+
3767
+ Read more about it in the
3768
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
3769
+ """
3770
+ ),
3771
+ ] = None,
3772
+ tags: Annotated[
3773
+ Optional[list[Union[str, Enum]]],
3774
+ Doc(
3775
+ """
3776
+ A list of tags to be applied to the *path operation*.
3777
+
3778
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3779
+
3780
+ Read more about it in the
3781
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
3782
+ """
3783
+ ),
3784
+ ] = None,
3785
+ dependencies: Annotated[
3786
+ Optional[Sequence[params.Depends]],
3787
+ Doc(
3788
+ """
3789
+ A list of dependencies (using `Depends()`) to be applied to the
3790
+ *path operation*.
3791
+
3792
+ Read more about it in the
3793
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
3794
+ """
3795
+ ),
3796
+ ] = None,
3797
+ summary: Annotated[
3798
+ Optional[str],
3799
+ Doc(
3800
+ """
3801
+ A summary for the *path operation*.
3802
+
3803
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3804
+
3805
+ Read more about it in the
3806
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3807
+ """
3808
+ ),
3809
+ ] = None,
3810
+ description: Annotated[
3811
+ Optional[str],
3812
+ Doc(
3813
+ """
3814
+ A description for the *path operation*.
3815
+
3816
+ If not provided, it will be extracted automatically from the docstring
3817
+ of the *path operation function*.
3818
+
3819
+ It can contain Markdown.
3820
+
3821
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3822
+
3823
+ Read more about it in the
3824
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3825
+ """
3826
+ ),
3827
+ ] = None,
3828
+ response_description: Annotated[
3829
+ str,
3830
+ Doc(
3831
+ """
3832
+ The description for the default response.
3833
+
3834
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3835
+ """
3836
+ ),
3837
+ ] = "Successful Response",
3838
+ responses: Annotated[
3839
+ Optional[dict[Union[int, str], dict[str, Any]]],
3840
+ Doc(
3841
+ """
3842
+ Additional responses that could be returned by this *path operation*.
3843
+
3844
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3845
+ """
3846
+ ),
3847
+ ] = None,
3848
+ deprecated: Annotated[
3849
+ Optional[bool],
3850
+ Doc(
3851
+ """
3852
+ Mark this *path operation* as deprecated.
3853
+
3854
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3855
+ """
3856
+ ),
3857
+ ] = None,
3858
+ operation_id: Annotated[
3859
+ Optional[str],
3860
+ Doc(
3861
+ """
3862
+ Custom operation ID to be used by this *path operation*.
3863
+
3864
+ By default, it is generated automatically.
3865
+
3866
+ If you provide a custom operation ID, you need to make sure it is
3867
+ unique for the whole API.
3868
+
3869
+ You can customize the
3870
+ operation ID generation with the parameter
3871
+ `generate_unique_id_function` in the `FastAPI` class.
3872
+
3873
+ Read more about it in the
3874
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3875
+ """
3876
+ ),
3877
+ ] = None,
3878
+ response_model_include: Annotated[
3879
+ Optional[IncEx],
3880
+ Doc(
3881
+ """
3882
+ Configuration passed to Pydantic to include only certain fields in the
3883
+ response data.
3884
+
3885
+ Read more about it in the
3886
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3887
+ """
3888
+ ),
3889
+ ] = None,
3890
+ response_model_exclude: Annotated[
3891
+ Optional[IncEx],
3892
+ Doc(
3893
+ """
3894
+ Configuration passed to Pydantic to exclude certain fields in the
3895
+ response data.
3896
+
3897
+ Read more about it in the
3898
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3899
+ """
3900
+ ),
3901
+ ] = None,
3902
+ response_model_by_alias: Annotated[
3903
+ bool,
3904
+ Doc(
3905
+ """
3906
+ Configuration passed to Pydantic to define if the response model
3907
+ should be serialized by alias when an alias is used.
3908
+
3909
+ Read more about it in the
3910
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3911
+ """
3912
+ ),
3913
+ ] = True,
3914
+ response_model_exclude_unset: Annotated[
3915
+ bool,
3916
+ Doc(
3917
+ """
3918
+ Configuration passed to Pydantic to define if the response data
3919
+ should have all the fields, including the ones that were not set and
3920
+ have their default values. This is different from
3921
+ `response_model_exclude_defaults` in that if the fields are set,
3922
+ they will be included in the response, even if the value is the same
3923
+ as the default.
3924
+
3925
+ When `True`, default values are omitted from the response.
3926
+
3927
+ Read more about it in the
3928
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3929
+ """
3930
+ ),
3931
+ ] = False,
3932
+ response_model_exclude_defaults: Annotated[
3933
+ bool,
3934
+ Doc(
3935
+ """
3936
+ Configuration passed to Pydantic to define if the response data
3937
+ should have all the fields, including the ones that have the same value
3938
+ as the default. This is different from `response_model_exclude_unset`
3939
+ in that if the fields are set but contain the same default values,
3940
+ they will be excluded from the response.
3941
+
3942
+ When `True`, default values are omitted from the response.
3943
+
3944
+ Read more about it in the
3945
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3946
+ """
3947
+ ),
3948
+ ] = False,
3949
+ response_model_exclude_none: Annotated[
3950
+ bool,
3951
+ Doc(
3952
+ """
3953
+ Configuration passed to Pydantic to define if the response data should
3954
+ exclude fields set to `None`.
3955
+
3956
+ This is much simpler (less smart) than `response_model_exclude_unset`
3957
+ and `response_model_exclude_defaults`. You probably want to use one of
3958
+ those two instead of this one, as those allow returning `None` values
3959
+ when it makes sense.
3960
+
3961
+ Read more about it in the
3962
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
3963
+ """
3964
+ ),
3965
+ ] = False,
3966
+ include_in_schema: Annotated[
3967
+ bool,
3968
+ Doc(
3969
+ """
3970
+ Include this *path operation* in the generated OpenAPI schema.
3971
+
3972
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
3973
+
3974
+ Read more about it in the
3975
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
3976
+ """
3977
+ ),
3978
+ ] = True,
3979
+ response_class: Annotated[
3980
+ type[Response],
3981
+ Doc(
3982
+ """
3983
+ Response class to be used for this *path operation*.
3984
+
3985
+ This will not be used if you return a response directly.
3986
+
3987
+ Read more about it in the
3988
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
3989
+ """
3990
+ ),
3991
+ ] = Default(JSONResponse),
3992
+ name: Annotated[
3993
+ Optional[str],
3994
+ Doc(
3995
+ """
3996
+ Name for this *path operation*. Only used internally.
3997
+ """
3998
+ ),
3999
+ ] = None,
4000
+ callbacks: Annotated[
4001
+ Optional[list[BaseRoute]],
4002
+ Doc(
4003
+ """
4004
+ List of *path operations* that will be used as OpenAPI callbacks.
4005
+
4006
+ This is only for OpenAPI documentation, the callbacks won't be used
4007
+ directly.
4008
+
4009
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4010
+
4011
+ Read more about it in the
4012
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
4013
+ """
4014
+ ),
4015
+ ] = None,
4016
+ openapi_extra: Annotated[
4017
+ Optional[dict[str, Any]],
4018
+ Doc(
4019
+ """
4020
+ Extra metadata to be included in the OpenAPI schema for this *path
4021
+ operation*.
4022
+
4023
+ Read more about it in the
4024
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
4025
+ """
4026
+ ),
4027
+ ] = None,
4028
+ generate_unique_id_function: Annotated[
4029
+ Callable[[APIRoute], str],
4030
+ Doc(
4031
+ """
4032
+ Customize the function used to generate unique IDs for the *path
4033
+ operations* shown in the generated OpenAPI.
4034
+
4035
+ This is particularly useful when automatically generating clients or
4036
+ SDKs for your API.
4037
+
4038
+ Read more about it in the
4039
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
4040
+ """
4041
+ ),
4042
+ ] = Default(generate_unique_id),
4043
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4044
+ """
4045
+ Add a *path operation* using an HTTP PATCH operation.
4046
+
4047
+ ## Example
4048
+
4049
+ ```python
4050
+ from fastapi import APIRouter, FastAPI
4051
+ from pydantic import BaseModel
4052
+
4053
+ class Item(BaseModel):
4054
+ name: str
4055
+ description: str | None = None
4056
+
4057
+ app = FastAPI()
4058
+ router = APIRouter()
4059
+
4060
+ @router.patch("/items/")
4061
+ def update_item(item: Item):
4062
+ return {"message": "Item updated in place"}
4063
+
4064
+ app.include_router(router)
4065
+ ```
4066
+ """
4067
+ return self.api_route(
4068
+ path=path,
4069
+ response_model=response_model,
4070
+ status_code=status_code,
4071
+ tags=tags,
4072
+ dependencies=dependencies,
4073
+ summary=summary,
4074
+ description=description,
4075
+ response_description=response_description,
4076
+ responses=responses,
4077
+ deprecated=deprecated,
4078
+ methods=["PATCH"],
4079
+ operation_id=operation_id,
4080
+ response_model_include=response_model_include,
4081
+ response_model_exclude=response_model_exclude,
4082
+ response_model_by_alias=response_model_by_alias,
4083
+ response_model_exclude_unset=response_model_exclude_unset,
4084
+ response_model_exclude_defaults=response_model_exclude_defaults,
4085
+ response_model_exclude_none=response_model_exclude_none,
4086
+ include_in_schema=include_in_schema,
4087
+ response_class=response_class,
4088
+ name=name,
4089
+ callbacks=callbacks,
4090
+ openapi_extra=openapi_extra,
4091
+ generate_unique_id_function=generate_unique_id_function,
4092
+ )
4093
+
4094
+ def trace(
4095
+ self,
4096
+ path: Annotated[
4097
+ str,
4098
+ Doc(
4099
+ """
4100
+ The URL path to be used for this *path operation*.
4101
+
4102
+ For example, in `http://example.com/items`, the path is `/items`.
4103
+ """
4104
+ ),
4105
+ ],
4106
+ *,
4107
+ response_model: Annotated[
4108
+ Any,
4109
+ Doc(
4110
+ """
4111
+ The type to use for the response.
4112
+
4113
+ It could be any valid Pydantic *field* type. So, it doesn't have to
4114
+ be a Pydantic model, it could be other things, like a `list`, `dict`,
4115
+ etc.
4116
+
4117
+ It will be used for:
4118
+
4119
+ * Documentation: the generated OpenAPI (and the UI at `/docs`) will
4120
+ show it as the response (JSON Schema).
4121
+ * Serialization: you could return an arbitrary object and the
4122
+ `response_model` would be used to serialize that object into the
4123
+ corresponding JSON.
4124
+ * Filtering: the JSON sent to the client will only contain the data
4125
+ (fields) defined in the `response_model`. If you returned an object
4126
+ that contains an attribute `password` but the `response_model` does
4127
+ not include that field, the JSON sent to the client would not have
4128
+ that `password`.
4129
+ * Validation: whatever you return will be serialized with the
4130
+ `response_model`, converting any data as necessary to generate the
4131
+ corresponding JSON. But if the data in the object returned is not
4132
+ valid, that would mean a violation of the contract with the client,
4133
+ so it's an error from the API developer. So, FastAPI will raise an
4134
+ error and return a 500 error code (Internal Server Error).
4135
+
4136
+ Read more about it in the
4137
+ [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
4138
+ """
4139
+ ),
4140
+ ] = Default(None),
4141
+ status_code: Annotated[
4142
+ Optional[int],
4143
+ Doc(
4144
+ """
4145
+ The default status code to be used for the response.
4146
+
4147
+ You could override the status code by returning a response directly.
4148
+
4149
+ Read more about it in the
4150
+ [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
4151
+ """
4152
+ ),
4153
+ ] = None,
4154
+ tags: Annotated[
4155
+ Optional[list[Union[str, Enum]]],
4156
+ Doc(
4157
+ """
4158
+ A list of tags to be applied to the *path operation*.
4159
+
4160
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4161
+
4162
+ Read more about it in the
4163
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
4164
+ """
4165
+ ),
4166
+ ] = None,
4167
+ dependencies: Annotated[
4168
+ Optional[Sequence[params.Depends]],
4169
+ Doc(
4170
+ """
4171
+ A list of dependencies (using `Depends()`) to be applied to the
4172
+ *path operation*.
4173
+
4174
+ Read more about it in the
4175
+ [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
4176
+ """
4177
+ ),
4178
+ ] = None,
4179
+ summary: Annotated[
4180
+ Optional[str],
4181
+ Doc(
4182
+ """
4183
+ A summary for the *path operation*.
4184
+
4185
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4186
+
4187
+ Read more about it in the
4188
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
4189
+ """
4190
+ ),
4191
+ ] = None,
4192
+ description: Annotated[
4193
+ Optional[str],
4194
+ Doc(
4195
+ """
4196
+ A description for the *path operation*.
4197
+
4198
+ If not provided, it will be extracted automatically from the docstring
4199
+ of the *path operation function*.
4200
+
4201
+ It can contain Markdown.
4202
+
4203
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4204
+
4205
+ Read more about it in the
4206
+ [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
4207
+ """
4208
+ ),
4209
+ ] = None,
4210
+ response_description: Annotated[
4211
+ str,
4212
+ Doc(
4213
+ """
4214
+ The description for the default response.
4215
+
4216
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4217
+ """
4218
+ ),
4219
+ ] = "Successful Response",
4220
+ responses: Annotated[
4221
+ Optional[dict[Union[int, str], dict[str, Any]]],
4222
+ Doc(
4223
+ """
4224
+ Additional responses that could be returned by this *path operation*.
4225
+
4226
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4227
+ """
4228
+ ),
4229
+ ] = None,
4230
+ deprecated: Annotated[
4231
+ Optional[bool],
4232
+ Doc(
4233
+ """
4234
+ Mark this *path operation* as deprecated.
4235
+
4236
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4237
+ """
4238
+ ),
4239
+ ] = None,
4240
+ operation_id: Annotated[
4241
+ Optional[str],
4242
+ Doc(
4243
+ """
4244
+ Custom operation ID to be used by this *path operation*.
4245
+
4246
+ By default, it is generated automatically.
4247
+
4248
+ If you provide a custom operation ID, you need to make sure it is
4249
+ unique for the whole API.
4250
+
4251
+ You can customize the
4252
+ operation ID generation with the parameter
4253
+ `generate_unique_id_function` in the `FastAPI` class.
4254
+
4255
+ Read more about it in the
4256
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
4257
+ """
4258
+ ),
4259
+ ] = None,
4260
+ response_model_include: Annotated[
4261
+ Optional[IncEx],
4262
+ Doc(
4263
+ """
4264
+ Configuration passed to Pydantic to include only certain fields in the
4265
+ response data.
4266
+
4267
+ Read more about it in the
4268
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
4269
+ """
4270
+ ),
4271
+ ] = None,
4272
+ response_model_exclude: Annotated[
4273
+ Optional[IncEx],
4274
+ Doc(
4275
+ """
4276
+ Configuration passed to Pydantic to exclude certain fields in the
4277
+ response data.
4278
+
4279
+ Read more about it in the
4280
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
4281
+ """
4282
+ ),
4283
+ ] = None,
4284
+ response_model_by_alias: Annotated[
4285
+ bool,
4286
+ Doc(
4287
+ """
4288
+ Configuration passed to Pydantic to define if the response model
4289
+ should be serialized by alias when an alias is used.
4290
+
4291
+ Read more about it in the
4292
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
4293
+ """
4294
+ ),
4295
+ ] = True,
4296
+ response_model_exclude_unset: Annotated[
4297
+ bool,
4298
+ Doc(
4299
+ """
4300
+ Configuration passed to Pydantic to define if the response data
4301
+ should have all the fields, including the ones that were not set and
4302
+ have their default values. This is different from
4303
+ `response_model_exclude_defaults` in that if the fields are set,
4304
+ they will be included in the response, even if the value is the same
4305
+ as the default.
4306
+
4307
+ When `True`, default values are omitted from the response.
4308
+
4309
+ Read more about it in the
4310
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
4311
+ """
4312
+ ),
4313
+ ] = False,
4314
+ response_model_exclude_defaults: Annotated[
4315
+ bool,
4316
+ Doc(
4317
+ """
4318
+ Configuration passed to Pydantic to define if the response data
4319
+ should have all the fields, including the ones that have the same value
4320
+ as the default. This is different from `response_model_exclude_unset`
4321
+ in that if the fields are set but contain the same default values,
4322
+ they will be excluded from the response.
4323
+
4324
+ When `True`, default values are omitted from the response.
4325
+
4326
+ Read more about it in the
4327
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
4328
+ """
4329
+ ),
4330
+ ] = False,
4331
+ response_model_exclude_none: Annotated[
4332
+ bool,
4333
+ Doc(
4334
+ """
4335
+ Configuration passed to Pydantic to define if the response data should
4336
+ exclude fields set to `None`.
4337
+
4338
+ This is much simpler (less smart) than `response_model_exclude_unset`
4339
+ and `response_model_exclude_defaults`. You probably want to use one of
4340
+ those two instead of this one, as those allow returning `None` values
4341
+ when it makes sense.
4342
+
4343
+ Read more about it in the
4344
+ [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
4345
+ """
4346
+ ),
4347
+ ] = False,
4348
+ include_in_schema: Annotated[
4349
+ bool,
4350
+ Doc(
4351
+ """
4352
+ Include this *path operation* in the generated OpenAPI schema.
4353
+
4354
+ This affects the generated OpenAPI (e.g. visible at `/docs`).
4355
+
4356
+ Read more about it in the
4357
+ [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).
4358
+ """
4359
+ ),
4360
+ ] = True,
4361
+ response_class: Annotated[
4362
+ type[Response],
4363
+ Doc(
4364
+ """
4365
+ Response class to be used for this *path operation*.
4366
+
4367
+ This will not be used if you return a response directly.
4368
+
4369
+ Read more about it in the
4370
+ [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
4371
+ """
4372
+ ),
4373
+ ] = Default(JSONResponse),
4374
+ name: Annotated[
4375
+ Optional[str],
4376
+ Doc(
4377
+ """
4378
+ Name for this *path operation*. Only used internally.
4379
+ """
4380
+ ),
4381
+ ] = None,
4382
+ callbacks: Annotated[
4383
+ Optional[list[BaseRoute]],
4384
+ Doc(
4385
+ """
4386
+ List of *path operations* that will be used as OpenAPI callbacks.
4387
+
4388
+ This is only for OpenAPI documentation, the callbacks won't be used
4389
+ directly.
4390
+
4391
+ It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4392
+
4393
+ Read more about it in the
4394
+ [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
4395
+ """
4396
+ ),
4397
+ ] = None,
4398
+ openapi_extra: Annotated[
4399
+ Optional[dict[str, Any]],
4400
+ Doc(
4401
+ """
4402
+ Extra metadata to be included in the OpenAPI schema for this *path
4403
+ operation*.
4404
+
4405
+ Read more about it in the
4406
+ [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
4407
+ """
4408
+ ),
4409
+ ] = None,
4410
+ generate_unique_id_function: Annotated[
4411
+ Callable[[APIRoute], str],
4412
+ Doc(
4413
+ """
4414
+ Customize the function used to generate unique IDs for the *path
4415
+ operations* shown in the generated OpenAPI.
4416
+
4417
+ This is particularly useful when automatically generating clients or
4418
+ SDKs for your API.
4419
+
4420
+ Read more about it in the
4421
+ [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
4422
+ """
4423
+ ),
4424
+ ] = Default(generate_unique_id),
4425
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4426
+ """
4427
+ Add a *path operation* using an HTTP TRACE operation.
4428
+
4429
+ ## Example
4430
+
4431
+ ```python
4432
+ from fastapi import APIRouter, FastAPI
4433
+ from pydantic import BaseModel
4434
+
4435
+ class Item(BaseModel):
4436
+ name: str
4437
+ description: str | None = None
4438
+
4439
+ app = FastAPI()
4440
+ router = APIRouter()
4441
+
4442
+ @router.trace("/items/{item_id}")
4443
+ def trace_item(item_id: str):
4444
+ return None
4445
+
4446
+ app.include_router(router)
4447
+ ```
4448
+ """
4449
+ return self.api_route(
4450
+ path=path,
4451
+ response_model=response_model,
4452
+ status_code=status_code,
4453
+ tags=tags,
4454
+ dependencies=dependencies,
4455
+ summary=summary,
4456
+ description=description,
4457
+ response_description=response_description,
4458
+ responses=responses,
4459
+ deprecated=deprecated,
4460
+ methods=["TRACE"],
4461
+ operation_id=operation_id,
4462
+ response_model_include=response_model_include,
4463
+ response_model_exclude=response_model_exclude,
4464
+ response_model_by_alias=response_model_by_alias,
4465
+ response_model_exclude_unset=response_model_exclude_unset,
4466
+ response_model_exclude_defaults=response_model_exclude_defaults,
4467
+ response_model_exclude_none=response_model_exclude_none,
4468
+ include_in_schema=include_in_schema,
4469
+ response_class=response_class,
4470
+ name=name,
4471
+ callbacks=callbacks,
4472
+ openapi_extra=openapi_extra,
4473
+ generate_unique_id_function=generate_unique_id_function,
4474
+ )
4475
+
4476
+ @deprecated(
4477
+ """
4478
+ on_event is deprecated, use lifespan event handlers instead.
4479
+
4480
+ Read more about it in the
4481
+ [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
4482
+ """
4483
+ )
4484
+ def on_event(
4485
+ self,
4486
+ event_type: Annotated[
4487
+ str,
4488
+ Doc(
4489
+ """
4490
+ The type of event. `startup` or `shutdown`.
4491
+ """
4492
+ ),
4493
+ ],
4494
+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4495
+ """
4496
+ Add an event handler for the router.
4497
+
4498
+ `on_event` is deprecated, use `lifespan` event handlers instead.
4499
+
4500
+ Read more about it in the
4501
+ [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
4502
+ """
4503
+
4504
+ def decorator(func: DecoratedCallable) -> DecoratedCallable:
4505
+ self.add_event_handler(event_type, func)
4506
+ return func
4507
+
4508
+ return decorator