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