You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

4589 lines
172 KiB

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