Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

4441 linhas
172 KiB

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