Coverage for fastapi/applications.py: 100%
152 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-08-08 03:53 +0000
1from enum import Enum 1abcde
2from typing import ( 1abcde
3 Any,
4 Awaitable,
5 Callable,
6 Coroutine,
7 Dict,
8 List,
9 Optional,
10 Sequence,
11 Type,
12 TypeVar,
13 Union,
14)
16from fastapi import routing 1abcde
17from fastapi.datastructures import Default, DefaultPlaceholder 1abcde
18from fastapi.exception_handlers import ( 1abcde
19 http_exception_handler,
20 request_validation_exception_handler,
21 websocket_request_validation_exception_handler,
22)
23from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError 1abcde
24from fastapi.logger import logger 1abcde
25from fastapi.openapi.docs import ( 1abcde
26 get_redoc_html,
27 get_swagger_ui_html,
28 get_swagger_ui_oauth2_redirect_html,
29)
30from fastapi.openapi.utils import get_openapi 1abcde
31from fastapi.params import Depends 1abcde
32from fastapi.types import DecoratedCallable, IncEx 1abcde
33from fastapi.utils import generate_unique_id 1abcde
34from starlette.applications import Starlette 1abcde
35from starlette.datastructures import State 1abcde
36from starlette.exceptions import HTTPException 1abcde
37from starlette.middleware import Middleware 1abcde
38from starlette.middleware.base import BaseHTTPMiddleware 1abcde
39from starlette.requests import Request 1abcde
40from starlette.responses import HTMLResponse, JSONResponse, Response 1abcde
41from starlette.routing import BaseRoute 1abcde
42from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send 1abcde
43from typing_extensions import Annotated, Doc, deprecated 1abcde
45AppType = TypeVar("AppType", bound="FastAPI") 1abcde
48class FastAPI(Starlette): 1abcde
49 """
50 `FastAPI` app class, the main entrypoint to use FastAPI.
52 Read more in the
53 [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
55 ## Example
57 ```python
58 from fastapi import FastAPI
60 app = FastAPI()
61 ```
62 """
64 def __init__( 1abcde
65 self: AppType,
66 *,
67 debug: Annotated[
68 bool,
69 Doc(
70 """
71 Boolean indicating if debug tracebacks should be returned on server
72 errors.
74 Read more in the
75 [Starlette docs for Applications](https://www.starlette.io/applications/#instantiating-the-application).
76 """
77 ),
78 ] = False,
79 routes: Annotated[
80 Optional[List[BaseRoute]],
81 Doc(
82 """
83 **Note**: you probably shouldn't use this parameter, it is inherited
84 from Starlette and supported for compatibility.
86 ---
88 A list of routes to serve incoming HTTP and WebSocket requests.
89 """
90 ),
91 deprecated(
92 """
93 You normally wouldn't use this parameter with FastAPI, it is inherited
94 from Starlette and supported for compatibility.
96 In FastAPI, you normally would use the *path operation methods*,
97 like `app.get()`, `app.post()`, etc.
98 """
99 ),
100 ] = None,
101 title: Annotated[
102 str,
103 Doc(
104 """
105 The title of the API.
107 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
109 Read more in the
110 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
112 **Example**
114 ```python
115 from fastapi import FastAPI
117 app = FastAPI(title="ChimichangApp")
118 ```
119 """
120 ),
121 ] = "FastAPI",
122 summary: Annotated[
123 Optional[str],
124 Doc(
125 """
126 A short summary of the API.
128 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
130 Read more in the
131 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
133 **Example**
135 ```python
136 from fastapi import FastAPI
138 app = FastAPI(summary="Deadpond's favorite app. Nuff said.")
139 ```
140 """
141 ),
142 ] = None,
143 description: Annotated[
144 str,
145 Doc(
146 '''
147 A description of the API. Supports Markdown (using
148 [CommonMark syntax](https://commonmark.org/)).
150 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
152 Read more in the
153 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
155 **Example**
157 ```python
158 from fastapi import FastAPI
160 app = FastAPI(
161 description="""
162 ChimichangApp API helps you do awesome stuff. 🚀
164 ## Items
166 You can **read items**.
168 ## Users
170 You will be able to:
172 * **Create users** (_not implemented_).
173 * **Read users** (_not implemented_).
175 """
176 )
177 ```
178 '''
179 ),
180 ] = "",
181 version: Annotated[
182 str,
183 Doc(
184 """
185 The version of the API.
187 **Note** This is the version of your application, not the version of
188 the OpenAPI specification nor the version of FastAPI being used.
190 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
192 Read more in the
193 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
195 **Example**
197 ```python
198 from fastapi import FastAPI
200 app = FastAPI(version="0.0.1")
201 ```
202 """
203 ),
204 ] = "0.1.0",
205 openapi_url: Annotated[
206 Optional[str],
207 Doc(
208 """
209 The URL where the OpenAPI schema will be served from.
211 If you set it to `None`, no OpenAPI schema will be served publicly, and
212 the default automatic endpoints `/docs` and `/redoc` will also be
213 disabled.
215 Read more in the
216 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).
218 **Example**
220 ```python
221 from fastapi import FastAPI
223 app = FastAPI(openapi_url="/api/v1/openapi.json")
224 ```
225 """
226 ),
227 ] = "/openapi.json",
228 openapi_tags: Annotated[
229 Optional[List[Dict[str, Any]]],
230 Doc(
231 """
232 A list of tags used by OpenAPI, these are the same `tags` you can set
233 in the *path operations*, like:
235 * `@app.get("/users/", tags=["users"])`
236 * `@app.get("/items/", tags=["items"])`
238 The order of the tags can be used to specify the order shown in
239 tools like Swagger UI, used in the automatic path `/docs`.
241 It's not required to specify all the tags used.
243 The tags that are not declared MAY be organized randomly or based
244 on the tools' logic. Each tag name in the list MUST be unique.
246 The value of each item is a `dict` containing:
248 * `name`: The name of the tag.
249 * `description`: A short description of the tag.
250 [CommonMark syntax](https://commonmark.org/) MAY be used for rich
251 text representation.
252 * `externalDocs`: Additional external documentation for this tag. If
253 provided, it would contain a `dict` with:
254 * `description`: A short description of the target documentation.
255 [CommonMark syntax](https://commonmark.org/) MAY be used for
256 rich text representation.
257 * `url`: The URL for the target documentation. Value MUST be in
258 the form of a URL.
260 Read more in the
261 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).
263 **Example**
265 ```python
266 from fastapi import FastAPI
268 tags_metadata = [
269 {
270 "name": "users",
271 "description": "Operations with users. The **login** logic is also here.",
272 },
273 {
274 "name": "items",
275 "description": "Manage items. So _fancy_ they have their own docs.",
276 "externalDocs": {
277 "description": "Items external docs",
278 "url": "https://fastapi.tiangolo.com/",
279 },
280 },
281 ]
283 app = FastAPI(openapi_tags=tags_metadata)
284 ```
285 """
286 ),
287 ] = None,
288 servers: Annotated[
289 Optional[List[Dict[str, Union[str, Any]]]],
290 Doc(
291 """
292 A `list` of `dict`s with connectivity information to a target server.
294 You would use it, for example, if your application is served from
295 different domains and you want to use the same Swagger UI in the
296 browser to interact with each of them (instead of having multiple
297 browser tabs open). Or if you want to leave fixed the possible URLs.
299 If the servers `list` is not provided, or is an empty `list`, the
300 default value would be a `dict` with a `url` value of `/`.
302 Each item in the `list` is a `dict` containing:
304 * `url`: A URL to the target host. This URL supports Server Variables
305 and MAY be relative, to indicate that the host location is relative
306 to the location where the OpenAPI document is being served. Variable
307 substitutions will be made when a variable is named in `{`brackets`}`.
308 * `description`: An optional string describing the host designated by
309 the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for
310 rich text representation.
311 * `variables`: A `dict` between a variable name and its value. The value
312 is used for substitution in the server's URL template.
314 Read more in the
315 [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).
317 **Example**
319 ```python
320 from fastapi import FastAPI
322 app = FastAPI(
323 servers=[
324 {"url": "https://stag.example.com", "description": "Staging environment"},
325 {"url": "https://prod.example.com", "description": "Production environment"},
326 ]
327 )
328 ```
329 """
330 ),
331 ] = None,
332 dependencies: Annotated[
333 Optional[Sequence[Depends]],
334 Doc(
335 """
336 A list of global dependencies, they will be applied to each
337 *path operation*, including in sub-routers.
339 Read more about it in the
340 [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).
342 **Example**
344 ```python
345 from fastapi import Depends, FastAPI
347 from .dependencies import func_dep_1, func_dep_2
349 app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])
350 ```
351 """
352 ),
353 ] = None,
354 default_response_class: Annotated[
355 Type[Response],
356 Doc(
357 """
358 The default response class to be used.
360 Read more in the
361 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
363 **Example**
365 ```python
366 from fastapi import FastAPI
367 from fastapi.responses import ORJSONResponse
369 app = FastAPI(default_response_class=ORJSONResponse)
370 ```
371 """
372 ),
373 ] = Default(JSONResponse),
374 redirect_slashes: Annotated[
375 bool,
376 Doc(
377 """
378 Whether to detect and redirect slashes in URLs when the client doesn't
379 use the same format.
381 **Example**
383 ```python
384 from fastapi import FastAPI
386 app = FastAPI(redirect_slashes=True) # the default
388 @app.get("/items/")
389 async def read_items():
390 return [{"item_id": "Foo"}]
391 ```
393 With this app, if a client goes to `/items` (without a trailing slash),
394 they will be automatically redirected with an HTTP status code of 307
395 to `/items/`.
396 """
397 ),
398 ] = True,
399 docs_url: Annotated[
400 Optional[str],
401 Doc(
402 """
403 The path to the automatic interactive API documentation.
404 It is handled in the browser by Swagger UI.
406 The default URL is `/docs`. You can disable it by setting it to `None`.
408 If `openapi_url` is set to `None`, this will be automatically disabled.
410 Read more in the
411 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).
413 **Example**
415 ```python
416 from fastapi import FastAPI
418 app = FastAPI(docs_url="/documentation", redoc_url=None)
419 ```
420 """
421 ),
422 ] = "/docs",
423 redoc_url: Annotated[
424 Optional[str],
425 Doc(
426 """
427 The path to the alternative automatic interactive API documentation
428 provided by ReDoc.
430 The default URL is `/redoc`. You can disable it by setting it to `None`.
432 If `openapi_url` is set to `None`, this will be automatically disabled.
434 Read more in the
435 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).
437 **Example**
439 ```python
440 from fastapi import FastAPI
442 app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")
443 ```
444 """
445 ),
446 ] = "/redoc",
447 swagger_ui_oauth2_redirect_url: Annotated[
448 Optional[str],
449 Doc(
450 """
451 The OAuth2 redirect endpoint for the Swagger UI.
453 By default it is `/docs/oauth2-redirect`.
455 This is only used if you use OAuth2 (with the "Authorize" button)
456 with Swagger UI.
457 """
458 ),
459 ] = "/docs/oauth2-redirect",
460 swagger_ui_init_oauth: Annotated[
461 Optional[Dict[str, Any]],
462 Doc(
463 """
464 OAuth2 configuration for the Swagger UI, by default shown at `/docs`.
466 Read more about the available configuration options in the
467 [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).
468 """
469 ),
470 ] = None,
471 middleware: Annotated[
472 Optional[Sequence[Middleware]],
473 Doc(
474 """
475 List of middleware to be added when creating the application.
477 In FastAPI you would normally do this with `app.add_middleware()`
478 instead.
480 Read more in the
481 [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
482 """
483 ),
484 ] = None,
485 exception_handlers: Annotated[
486 Optional[
487 Dict[
488 Union[int, Type[Exception]],
489 Callable[[Request, Any], Coroutine[Any, Any, Response]],
490 ]
491 ],
492 Doc(
493 """
494 A dictionary with handlers for exceptions.
496 In FastAPI, you would normally use the decorator
497 `@app.exception_handler()`.
499 Read more in the
500 [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
501 """
502 ),
503 ] = None,
504 on_startup: Annotated[
505 Optional[Sequence[Callable[[], Any]]],
506 Doc(
507 """
508 A list of startup event handler functions.
510 You should instead use the `lifespan` handlers.
512 Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
513 """
514 ),
515 ] = None,
516 on_shutdown: Annotated[
517 Optional[Sequence[Callable[[], Any]]],
518 Doc(
519 """
520 A list of shutdown event handler functions.
522 You should instead use the `lifespan` handlers.
524 Read more in the
525 [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
526 """
527 ),
528 ] = None,
529 lifespan: Annotated[
530 Optional[Lifespan[AppType]],
531 Doc(
532 """
533 A `Lifespan` context manager handler. This replaces `startup` and
534 `shutdown` functions with a single context manager.
536 Read more in the
537 [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).
538 """
539 ),
540 ] = None,
541 terms_of_service: Annotated[
542 Optional[str],
543 Doc(
544 """
545 A URL to the Terms of Service for your API.
547 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
549 Read more at the
550 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
552 **Example**
554 ```python
555 app = FastAPI(terms_of_service="http://example.com/terms/")
556 ```
557 """
558 ),
559 ] = None,
560 contact: Annotated[
561 Optional[Dict[str, Union[str, Any]]],
562 Doc(
563 """
564 A dictionary with the contact information for the exposed API.
566 It can contain several fields.
568 * `name`: (`str`) The name of the contact person/organization.
569 * `url`: (`str`) A URL pointing to the contact information. MUST be in
570 the format of a URL.
571 * `email`: (`str`) The email address of the contact person/organization.
572 MUST be in the format of an email address.
574 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
576 Read more at the
577 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
579 **Example**
581 ```python
582 app = FastAPI(
583 contact={
584 "name": "Deadpoolio the Amazing",
585 "url": "http://x-force.example.com/contact/",
586 "email": "dp@x-force.example.com",
587 }
588 )
589 ```
590 """
591 ),
592 ] = None,
593 license_info: Annotated[
594 Optional[Dict[str, Union[str, Any]]],
595 Doc(
596 """
597 A dictionary with the license information for the exposed API.
599 It can contain several fields.
601 * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The
602 license name used for the API.
603 * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression
604 for the API. The `identifier` field is mutually exclusive of the `url`
605 field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.
606 * `url`: (`str`) A URL to the license used for the API. This MUST be
607 the format of a URL.
609 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
611 Read more at the
612 [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).
614 **Example**
616 ```python
617 app = FastAPI(
618 license_info={
619 "name": "Apache 2.0",
620 "url": "https://www.apache.org/licenses/LICENSE-2.0.html",
621 }
622 )
623 ```
624 """
625 ),
626 ] = None,
627 openapi_prefix: Annotated[
628 str,
629 Doc(
630 """
631 A URL prefix for the OpenAPI URL.
632 """
633 ),
634 deprecated(
635 """
636 "openapi_prefix" has been deprecated in favor of "root_path", which
637 follows more closely the ASGI standard, is simpler, and more
638 automatic.
639 """
640 ),
641 ] = "",
642 root_path: Annotated[
643 str,
644 Doc(
645 """
646 A path prefix handled by a proxy that is not seen by the application
647 but is seen by external clients, which affects things like Swagger UI.
649 Read more about it at the
650 [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).
652 **Example**
654 ```python
655 from fastapi import FastAPI
657 app = FastAPI(root_path="/api/v1")
658 ```
659 """
660 ),
661 ] = "",
662 root_path_in_servers: Annotated[
663 bool,
664 Doc(
665 """
666 To disable automatically generating the URLs in the `servers` field
667 in the autogenerated OpenAPI using the `root_path`.
669 Read more about it in the
670 [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root_path).
672 **Example**
674 ```python
675 from fastapi import FastAPI
677 app = FastAPI(root_path_in_servers=False)
678 ```
679 """
680 ),
681 ] = True,
682 responses: Annotated[
683 Optional[Dict[Union[int, str], Dict[str, Any]]],
684 Doc(
685 """
686 Additional responses to be shown in OpenAPI.
688 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
690 Read more about it in the
691 [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
693 And in the
694 [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
695 """
696 ),
697 ] = None,
698 callbacks: Annotated[
699 Optional[List[BaseRoute]],
700 Doc(
701 """
702 OpenAPI callbacks that should apply to all *path operations*.
704 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
706 Read more about it in the
707 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
708 """
709 ),
710 ] = None,
711 webhooks: Annotated[
712 Optional[routing.APIRouter],
713 Doc(
714 """
715 Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't
716 depend on specific *path operations*.
718 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
720 **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.
722 Read more about it in the
723 [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
724 """
725 ),
726 ] = None,
727 deprecated: Annotated[
728 Optional[bool],
729 Doc(
730 """
731 Mark all *path operations* as deprecated. You probably don't need it,
732 but it's available.
734 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
736 Read more about it in the
737 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
738 """
739 ),
740 ] = None,
741 include_in_schema: Annotated[
742 bool,
743 Doc(
744 """
745 To include (or not) all the *path operations* in the generated OpenAPI.
746 You probably don't need it, but it's available.
748 This affects the generated OpenAPI (e.g. visible at `/docs`).
750 Read more about it in the
751 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
752 """
753 ),
754 ] = True,
755 swagger_ui_parameters: Annotated[
756 Optional[Dict[str, Any]],
757 Doc(
758 """
759 Parameters to configure Swagger UI, the autogenerated interactive API
760 documentation (by default at `/docs`).
762 Read more about it in the
763 [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).
764 """
765 ),
766 ] = None,
767 generate_unique_id_function: Annotated[
768 Callable[[routing.APIRoute], str],
769 Doc(
770 """
771 Customize the function used to generate unique IDs for the *path
772 operations* shown in the generated OpenAPI.
774 This is particularly useful when automatically generating clients or
775 SDKs for your API.
777 Read more about it in the
778 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
779 """
780 ),
781 ] = Default(generate_unique_id),
782 separate_input_output_schemas: Annotated[
783 bool,
784 Doc(
785 """
786 Whether to generate separate OpenAPI schemas for request body and
787 response body when the results would be more precise.
789 This is particularly useful when automatically generating clients.
791 For example, if you have a model like:
793 ```python
794 from pydantic import BaseModel
796 class Item(BaseModel):
797 name: str
798 tags: list[str] = []
799 ```
801 When `Item` is used for input, a request body, `tags` is not required,
802 the client doesn't have to provide it.
804 But when using `Item` for output, for a response body, `tags` is always
805 available because it has a default value, even if it's just an empty
806 list. So, the client should be able to always expect it.
808 In this case, there would be two different schemas, one for input and
809 another one for output.
810 """
811 ),
812 ] = True,
813 **extra: Annotated[
814 Any,
815 Doc(
816 """
817 Extra keyword arguments to be stored in the app, not used by FastAPI
818 anywhere.
819 """
820 ),
821 ],
822 ) -> None:
823 self.debug = debug 1abcde
824 self.title = title 1abcde
825 self.summary = summary 1abcde
826 self.description = description 1abcde
827 self.version = version 1abcde
828 self.terms_of_service = terms_of_service 1abcde
829 self.contact = contact 1abcde
830 self.license_info = license_info 1abcde
831 self.openapi_url = openapi_url 1abcde
832 self.openapi_tags = openapi_tags 1abcde
833 self.root_path_in_servers = root_path_in_servers 1abcde
834 self.docs_url = docs_url 1abcde
835 self.redoc_url = redoc_url 1abcde
836 self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url 1abcde
837 self.swagger_ui_init_oauth = swagger_ui_init_oauth 1abcde
838 self.swagger_ui_parameters = swagger_ui_parameters 1abcde
839 self.servers = servers or [] 1abcde
840 self.separate_input_output_schemas = separate_input_output_schemas 1abcde
841 self.extra = extra 1abcde
842 self.openapi_version: Annotated[ 1abcde
843 str,
844 Doc(
845 """
846 The version string of OpenAPI.
848 FastAPI will generate OpenAPI version 3.1.0, and will output that as
849 the OpenAPI version. But some tools, even though they might be
850 compatible with OpenAPI 3.1.0, might not recognize it as a valid.
852 So you could override this value to trick those tools into using
853 the generated OpenAPI. Have in mind that this is a hack. But if you
854 avoid using features added in OpenAPI 3.1.0, it might work for your
855 use case.
857 This is not passed as a parameter to the `FastAPI` class to avoid
858 giving the false idea that FastAPI would generate a different OpenAPI
859 schema. It is only available as an attribute.
861 **Example**
863 ```python
864 from fastapi import FastAPI
866 app = FastAPI()
868 app.openapi_version = "3.0.2"
869 ```
870 """
871 ),
872 ] = "3.1.0"
873 self.openapi_schema: Optional[Dict[str, Any]] = None 1abcde
874 if self.openapi_url: 1abcde
875 assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" 1abcde
876 assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" 1abcde
877 # TODO: remove when discarding the openapi_prefix parameter
878 if openapi_prefix: 1abcde
879 logger.warning( 1abcde
880 '"openapi_prefix" has been deprecated in favor of "root_path", which '
881 "follows more closely the ASGI standard, is simpler, and more "
882 "automatic. Check the docs at "
883 "https://fastapi.tiangolo.com/advanced/sub-applications/"
884 )
885 self.webhooks: Annotated[ 1abcde
886 routing.APIRouter,
887 Doc(
888 """
889 The `app.webhooks` attribute is an `APIRouter` with the *path
890 operations* that will be used just for documentation of webhooks.
892 Read more about it in the
893 [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).
894 """
895 ),
896 ] = webhooks or routing.APIRouter()
897 self.root_path = root_path or openapi_prefix 1abcde
898 self.state: Annotated[ 1abcde
899 State,
900 Doc(
901 """
902 A state object for the application. This is the same object for the
903 entire application, it doesn't change from request to request.
905 You normally wouldn't use this in FastAPI, for most of the cases you
906 would instead use FastAPI dependencies.
908 This is simply inherited from Starlette.
910 Read more about it in the
911 [Starlette docs for Applications](https://www.starlette.io/applications/#storing-state-on-the-app-instance).
912 """
913 ),
914 ] = State()
915 self.dependency_overrides: Annotated[ 1abcde
916 Dict[Callable[..., Any], Callable[..., Any]],
917 Doc(
918 """
919 A dictionary with overrides for the dependencies.
921 Each key is the original dependency callable, and the value is the
922 actual dependency that should be called.
924 This is for testing, to replace expensive dependencies with testing
925 versions.
927 Read more about it in the
928 [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).
929 """
930 ),
931 ] = {}
932 self.router: routing.APIRouter = routing.APIRouter( 1abcde
933 routes=routes,
934 redirect_slashes=redirect_slashes,
935 dependency_overrides_provider=self,
936 on_startup=on_startup,
937 on_shutdown=on_shutdown,
938 lifespan=lifespan,
939 default_response_class=default_response_class,
940 dependencies=dependencies,
941 callbacks=callbacks,
942 deprecated=deprecated,
943 include_in_schema=include_in_schema,
944 responses=responses,
945 generate_unique_id_function=generate_unique_id_function,
946 )
947 self.exception_handlers: Dict[ 1abcde
948 Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
949 ] = {} if exception_handlers is None else dict(exception_handlers)
950 self.exception_handlers.setdefault(HTTPException, http_exception_handler) 1abcde
951 self.exception_handlers.setdefault( 1abcde
952 RequestValidationError, request_validation_exception_handler
953 )
954 self.exception_handlers.setdefault( 1abcde
955 WebSocketRequestValidationError,
956 # Starlette still has incorrect type specification for the handlers
957 websocket_request_validation_exception_handler, # type: ignore
958 )
960 self.user_middleware: List[Middleware] = ( 1abcde
961 [] if middleware is None else list(middleware)
962 )
963 self.middleware_stack: Union[ASGIApp, None] = None 1abcde
964 self.setup() 1abcde
966 def openapi(self) -> Dict[str, Any]: 1abcde
967 """
968 Generate the OpenAPI schema of the application. This is called by FastAPI
969 internally.
971 The first time it is called it stores the result in the attribute
972 `app.openapi_schema`, and next times it is called, it just returns that same
973 result. To avoid the cost of generating the schema every time.
975 If you need to modify the generated OpenAPI schema, you could modify it.
977 Read more in the
978 [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
979 """
980 if not self.openapi_schema: 1abcde
981 self.openapi_schema = get_openapi( 1abcde
982 title=self.title,
983 version=self.version,
984 openapi_version=self.openapi_version,
985 summary=self.summary,
986 description=self.description,
987 terms_of_service=self.terms_of_service,
988 contact=self.contact,
989 license_info=self.license_info,
990 routes=self.routes,
991 webhooks=self.webhooks.routes,
992 tags=self.openapi_tags,
993 servers=self.servers,
994 separate_input_output_schemas=self.separate_input_output_schemas,
995 )
996 return self.openapi_schema 1abcde
998 def setup(self) -> None: 1abcde
999 if self.openapi_url: 1abcde
1000 urls = (server_data.get("url") for server_data in self.servers) 1abcde
1001 server_urls = {url for url in urls if url} 1abcde
1003 async def openapi(req: Request) -> JSONResponse: 1abcde
1004 root_path = req.scope.get("root_path", "").rstrip("/") 1abcde
1005 if root_path not in server_urls: 1abcde
1006 if root_path and self.root_path_in_servers: 1abcde
1007 self.servers.insert(0, {"url": root_path}) 1abcde
1008 server_urls.add(root_path) 1abcde
1009 return JSONResponse(self.openapi()) 1abcde
1011 self.add_route(self.openapi_url, openapi, include_in_schema=False) 1abcde
1012 if self.openapi_url and self.docs_url: 1abcde
1014 async def swagger_ui_html(req: Request) -> HTMLResponse: 1abcde
1015 root_path = req.scope.get("root_path", "").rstrip("/") 1abcde
1016 openapi_url = root_path + self.openapi_url 1abcde
1017 oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url 1abcde
1018 if oauth2_redirect_url: 1abcde
1019 oauth2_redirect_url = root_path + oauth2_redirect_url 1abcde
1020 return get_swagger_ui_html( 1abcde
1021 openapi_url=openapi_url,
1022 title=f"{self.title} - Swagger UI",
1023 oauth2_redirect_url=oauth2_redirect_url,
1024 init_oauth=self.swagger_ui_init_oauth,
1025 swagger_ui_parameters=self.swagger_ui_parameters,
1026 )
1028 self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False) 1abcde
1030 if self.swagger_ui_oauth2_redirect_url: 1abcde
1032 async def swagger_ui_redirect(req: Request) -> HTMLResponse: 1abcde
1033 return get_swagger_ui_oauth2_redirect_html() 1abcde
1035 self.add_route( 1abcde
1036 self.swagger_ui_oauth2_redirect_url,
1037 swagger_ui_redirect,
1038 include_in_schema=False,
1039 )
1040 if self.openapi_url and self.redoc_url: 1abcde
1042 async def redoc_html(req: Request) -> HTMLResponse: 1abcde
1043 root_path = req.scope.get("root_path", "").rstrip("/") 1abcde
1044 openapi_url = root_path + self.openapi_url 1abcde
1045 return get_redoc_html( 1abcde
1046 openapi_url=openapi_url, title=f"{self.title} - ReDoc"
1047 )
1049 self.add_route(self.redoc_url, redoc_html, include_in_schema=False) 1abcde
1051 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: 1abcde
1052 if self.root_path: 1abcde
1053 scope["root_path"] = self.root_path 1abcde
1054 await super().__call__(scope, receive, send) 1abcde
1056 def add_api_route( 1abcde
1057 self,
1058 path: str,
1059 endpoint: Callable[..., Coroutine[Any, Any, Response]],
1060 *,
1061 response_model: Any = Default(None),
1062 status_code: Optional[int] = None,
1063 tags: Optional[List[Union[str, Enum]]] = None,
1064 dependencies: Optional[Sequence[Depends]] = None,
1065 summary: Optional[str] = None,
1066 description: Optional[str] = None,
1067 response_description: str = "Successful Response",
1068 responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
1069 deprecated: Optional[bool] = None,
1070 methods: Optional[List[str]] = None,
1071 operation_id: Optional[str] = None,
1072 response_model_include: Optional[IncEx] = None,
1073 response_model_exclude: Optional[IncEx] = None,
1074 response_model_by_alias: bool = True,
1075 response_model_exclude_unset: bool = False,
1076 response_model_exclude_defaults: bool = False,
1077 response_model_exclude_none: bool = False,
1078 include_in_schema: bool = True,
1079 response_class: Union[Type[Response], DefaultPlaceholder] = Default(
1080 JSONResponse
1081 ),
1082 name: Optional[str] = None,
1083 openapi_extra: Optional[Dict[str, Any]] = None,
1084 generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
1085 generate_unique_id
1086 ),
1087 ) -> None:
1088 self.router.add_api_route( 1abcde
1089 path,
1090 endpoint=endpoint,
1091 response_model=response_model,
1092 status_code=status_code,
1093 tags=tags,
1094 dependencies=dependencies,
1095 summary=summary,
1096 description=description,
1097 response_description=response_description,
1098 responses=responses,
1099 deprecated=deprecated,
1100 methods=methods,
1101 operation_id=operation_id,
1102 response_model_include=response_model_include,
1103 response_model_exclude=response_model_exclude,
1104 response_model_by_alias=response_model_by_alias,
1105 response_model_exclude_unset=response_model_exclude_unset,
1106 response_model_exclude_defaults=response_model_exclude_defaults,
1107 response_model_exclude_none=response_model_exclude_none,
1108 include_in_schema=include_in_schema,
1109 response_class=response_class,
1110 name=name,
1111 openapi_extra=openapi_extra,
1112 generate_unique_id_function=generate_unique_id_function,
1113 )
1115 def api_route( 1abcde
1116 self,
1117 path: str,
1118 *,
1119 response_model: Any = Default(None),
1120 status_code: Optional[int] = None,
1121 tags: Optional[List[Union[str, Enum]]] = None,
1122 dependencies: Optional[Sequence[Depends]] = None,
1123 summary: Optional[str] = None,
1124 description: Optional[str] = None,
1125 response_description: str = "Successful Response",
1126 responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,
1127 deprecated: Optional[bool] = None,
1128 methods: Optional[List[str]] = None,
1129 operation_id: Optional[str] = None,
1130 response_model_include: Optional[IncEx] = None,
1131 response_model_exclude: Optional[IncEx] = None,
1132 response_model_by_alias: bool = True,
1133 response_model_exclude_unset: bool = False,
1134 response_model_exclude_defaults: bool = False,
1135 response_model_exclude_none: bool = False,
1136 include_in_schema: bool = True,
1137 response_class: Type[Response] = Default(JSONResponse),
1138 name: Optional[str] = None,
1139 openapi_extra: Optional[Dict[str, Any]] = None,
1140 generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
1141 generate_unique_id
1142 ),
1143 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1144 def decorator(func: DecoratedCallable) -> DecoratedCallable: 1abcde
1145 self.router.add_api_route( 1abcde
1146 path,
1147 func,
1148 response_model=response_model,
1149 status_code=status_code,
1150 tags=tags,
1151 dependencies=dependencies,
1152 summary=summary,
1153 description=description,
1154 response_description=response_description,
1155 responses=responses,
1156 deprecated=deprecated,
1157 methods=methods,
1158 operation_id=operation_id,
1159 response_model_include=response_model_include,
1160 response_model_exclude=response_model_exclude,
1161 response_model_by_alias=response_model_by_alias,
1162 response_model_exclude_unset=response_model_exclude_unset,
1163 response_model_exclude_defaults=response_model_exclude_defaults,
1164 response_model_exclude_none=response_model_exclude_none,
1165 include_in_schema=include_in_schema,
1166 response_class=response_class,
1167 name=name,
1168 openapi_extra=openapi_extra,
1169 generate_unique_id_function=generate_unique_id_function,
1170 )
1171 return func 1abcde
1173 return decorator 1abcde
1175 def add_api_websocket_route( 1abcde
1176 self,
1177 path: str,
1178 endpoint: Callable[..., Any],
1179 name: Optional[str] = None,
1180 *,
1181 dependencies: Optional[Sequence[Depends]] = None,
1182 ) -> None:
1183 self.router.add_api_websocket_route( 1abcde
1184 path,
1185 endpoint,
1186 name=name,
1187 dependencies=dependencies,
1188 )
1190 def websocket( 1abcde
1191 self,
1192 path: Annotated[
1193 str,
1194 Doc(
1195 """
1196 WebSocket path.
1197 """
1198 ),
1199 ],
1200 name: Annotated[
1201 Optional[str],
1202 Doc(
1203 """
1204 A name for the WebSocket. Only used internally.
1205 """
1206 ),
1207 ] = None,
1208 *,
1209 dependencies: Annotated[
1210 Optional[Sequence[Depends]],
1211 Doc(
1212 """
1213 A list of dependencies (using `Depends()`) to be used for this
1214 WebSocket.
1216 Read more about it in the
1217 [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
1218 """
1219 ),
1220 ] = None,
1221 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1222 """
1223 Decorate a WebSocket function.
1225 Read more about it in the
1226 [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
1228 **Example**
1230 ```python
1231 from fastapi import FastAPI, WebSocket
1233 app = FastAPI()
1235 @app.websocket("/ws")
1236 async def websocket_endpoint(websocket: WebSocket):
1237 await websocket.accept()
1238 while True:
1239 data = await websocket.receive_text()
1240 await websocket.send_text(f"Message text was: {data}")
1241 ```
1242 """
1244 def decorator(func: DecoratedCallable) -> DecoratedCallable: 1abcde
1245 self.add_api_websocket_route( 1abcde
1246 path,
1247 func,
1248 name=name,
1249 dependencies=dependencies,
1250 )
1251 return func 1abcde
1253 return decorator 1abcde
1255 def include_router( 1abcde
1256 self,
1257 router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],
1258 *,
1259 prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
1260 tags: Annotated[
1261 Optional[List[Union[str, Enum]]],
1262 Doc(
1263 """
1264 A list of tags to be applied to all the *path operations* in this
1265 router.
1267 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1269 Read more about it in the
1270 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1271 """
1272 ),
1273 ] = None,
1274 dependencies: Annotated[
1275 Optional[Sequence[Depends]],
1276 Doc(
1277 """
1278 A list of dependencies (using `Depends()`) to be applied to all the
1279 *path operations* in this router.
1281 Read more about it in the
1282 [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).
1284 **Example**
1286 ```python
1287 from fastapi import Depends, FastAPI
1289 from .dependencies import get_token_header
1290 from .internal import admin
1292 app = FastAPI()
1294 app.include_router(
1295 admin.router,
1296 dependencies=[Depends(get_token_header)],
1297 )
1298 ```
1299 """
1300 ),
1301 ] = None,
1302 responses: Annotated[
1303 Optional[Dict[Union[int, str], Dict[str, Any]]],
1304 Doc(
1305 """
1306 Additional responses to be shown in OpenAPI.
1308 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1310 Read more about it in the
1311 [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).
1313 And in the
1314 [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).
1315 """
1316 ),
1317 ] = None,
1318 deprecated: Annotated[
1319 Optional[bool],
1320 Doc(
1321 """
1322 Mark all the *path operations* in this router as deprecated.
1324 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1326 **Example**
1328 ```python
1329 from fastapi import FastAPI
1331 from .internal import old_api
1333 app = FastAPI()
1335 app.include_router(
1336 old_api.router,
1337 deprecated=True,
1338 )
1339 ```
1340 """
1341 ),
1342 ] = None,
1343 include_in_schema: Annotated[
1344 bool,
1345 Doc(
1346 """
1347 Include (or not) all the *path operations* in this router in the
1348 generated OpenAPI schema.
1350 This affects the generated OpenAPI (e.g. visible at `/docs`).
1352 **Example**
1354 ```python
1355 from fastapi import FastAPI
1357 from .internal import old_api
1359 app = FastAPI()
1361 app.include_router(
1362 old_api.router,
1363 include_in_schema=False,
1364 )
1365 ```
1366 """
1367 ),
1368 ] = True,
1369 default_response_class: Annotated[
1370 Type[Response],
1371 Doc(
1372 """
1373 Default response class to be used for the *path operations* in this
1374 router.
1376 Read more in the
1377 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).
1379 **Example**
1381 ```python
1382 from fastapi import FastAPI
1383 from fastapi.responses import ORJSONResponse
1385 from .internal import old_api
1387 app = FastAPI()
1389 app.include_router(
1390 old_api.router,
1391 default_response_class=ORJSONResponse,
1392 )
1393 ```
1394 """
1395 ),
1396 ] = Default(JSONResponse),
1397 callbacks: Annotated[
1398 Optional[List[BaseRoute]],
1399 Doc(
1400 """
1401 List of *path operations* that will be used as OpenAPI callbacks.
1403 This is only for OpenAPI documentation, the callbacks won't be used
1404 directly.
1406 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1408 Read more about it in the
1409 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
1410 """
1411 ),
1412 ] = None,
1413 generate_unique_id_function: Annotated[
1414 Callable[[routing.APIRoute], str],
1415 Doc(
1416 """
1417 Customize the function used to generate unique IDs for the *path
1418 operations* shown in the generated OpenAPI.
1420 This is particularly useful when automatically generating clients or
1421 SDKs for your API.
1423 Read more about it in the
1424 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1425 """
1426 ),
1427 ] = Default(generate_unique_id),
1428 ) -> None:
1429 """
1430 Include an `APIRouter` in the same app.
1432 Read more about it in the
1433 [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
1435 ## Example
1437 ```python
1438 from fastapi import FastAPI
1440 from .users import users_router
1442 app = FastAPI()
1444 app.include_router(users_router)
1445 ```
1446 """
1447 self.router.include_router( 1abcde
1448 router,
1449 prefix=prefix,
1450 tags=tags,
1451 dependencies=dependencies,
1452 responses=responses,
1453 deprecated=deprecated,
1454 include_in_schema=include_in_schema,
1455 default_response_class=default_response_class,
1456 callbacks=callbacks,
1457 generate_unique_id_function=generate_unique_id_function,
1458 )
1460 def get( 1abcde
1461 self,
1462 path: Annotated[
1463 str,
1464 Doc(
1465 """
1466 The URL path to be used for this *path operation*.
1468 For example, in `http://example.com/items`, the path is `/items`.
1469 """
1470 ),
1471 ],
1472 *,
1473 response_model: Annotated[
1474 Any,
1475 Doc(
1476 """
1477 The type to use for the response.
1479 It could be any valid Pydantic *field* type. So, it doesn't have to
1480 be a Pydantic model, it could be other things, like a `list`, `dict`,
1481 etc.
1483 It will be used for:
1485 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
1486 show it as the response (JSON Schema).
1487 * Serialization: you could return an arbitrary object and the
1488 `response_model` would be used to serialize that object into the
1489 corresponding JSON.
1490 * Filtering: the JSON sent to the client will only contain the data
1491 (fields) defined in the `response_model`. If you returned an object
1492 that contains an attribute `password` but the `response_model` does
1493 not include that field, the JSON sent to the client would not have
1494 that `password`.
1495 * Validation: whatever you return will be serialized with the
1496 `response_model`, converting any data as necessary to generate the
1497 corresponding JSON. But if the data in the object returned is not
1498 valid, that would mean a violation of the contract with the client,
1499 so it's an error from the API developer. So, FastAPI will raise an
1500 error and return a 500 error code (Internal Server Error).
1502 Read more about it in the
1503 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
1504 """
1505 ),
1506 ] = Default(None),
1507 status_code: Annotated[
1508 Optional[int],
1509 Doc(
1510 """
1511 The default status code to be used for the response.
1513 You could override the status code by returning a response directly.
1515 Read more about it in the
1516 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
1517 """
1518 ),
1519 ] = None,
1520 tags: Annotated[
1521 Optional[List[Union[str, Enum]]],
1522 Doc(
1523 """
1524 A list of tags to be applied to the *path operation*.
1526 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1528 Read more about it in the
1529 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
1530 """
1531 ),
1532 ] = None,
1533 dependencies: Annotated[
1534 Optional[Sequence[Depends]],
1535 Doc(
1536 """
1537 A list of dependencies (using `Depends()`) to be applied to the
1538 *path operation*.
1540 Read more about it in the
1541 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
1542 """
1543 ),
1544 ] = None,
1545 summary: Annotated[
1546 Optional[str],
1547 Doc(
1548 """
1549 A summary for the *path operation*.
1551 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1553 Read more about it in the
1554 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1555 """
1556 ),
1557 ] = None,
1558 description: Annotated[
1559 Optional[str],
1560 Doc(
1561 """
1562 A description for the *path operation*.
1564 If not provided, it will be extracted automatically from the docstring
1565 of the *path operation function*.
1567 It can contain Markdown.
1569 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1571 Read more about it in the
1572 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1573 """
1574 ),
1575 ] = None,
1576 response_description: Annotated[
1577 str,
1578 Doc(
1579 """
1580 The description for the default response.
1582 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1583 """
1584 ),
1585 ] = "Successful Response",
1586 responses: Annotated[
1587 Optional[Dict[Union[int, str], Dict[str, Any]]],
1588 Doc(
1589 """
1590 Additional responses that could be returned by this *path operation*.
1592 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1593 """
1594 ),
1595 ] = None,
1596 deprecated: Annotated[
1597 Optional[bool],
1598 Doc(
1599 """
1600 Mark this *path operation* as deprecated.
1602 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1603 """
1604 ),
1605 ] = None,
1606 operation_id: Annotated[
1607 Optional[str],
1608 Doc(
1609 """
1610 Custom operation ID to be used by this *path operation*.
1612 By default, it is generated automatically.
1614 If you provide a custom operation ID, you need to make sure it is
1615 unique for the whole API.
1617 You can customize the
1618 operation ID generation with the parameter
1619 `generate_unique_id_function` in the `FastAPI` class.
1621 Read more about it in the
1622 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1623 """
1624 ),
1625 ] = None,
1626 response_model_include: Annotated[
1627 Optional[IncEx],
1628 Doc(
1629 """
1630 Configuration passed to Pydantic to include only certain fields in the
1631 response data.
1633 Read more about it in the
1634 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1635 """
1636 ),
1637 ] = None,
1638 response_model_exclude: Annotated[
1639 Optional[IncEx],
1640 Doc(
1641 """
1642 Configuration passed to Pydantic to exclude certain fields in the
1643 response data.
1645 Read more about it in the
1646 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1647 """
1648 ),
1649 ] = None,
1650 response_model_by_alias: Annotated[
1651 bool,
1652 Doc(
1653 """
1654 Configuration passed to Pydantic to define if the response model
1655 should be serialized by alias when an alias is used.
1657 Read more about it in the
1658 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
1659 """
1660 ),
1661 ] = True,
1662 response_model_exclude_unset: Annotated[
1663 bool,
1664 Doc(
1665 """
1666 Configuration passed to Pydantic to define if the response data
1667 should have all the fields, including the ones that were not set and
1668 have their default values. This is different from
1669 `response_model_exclude_defaults` in that if the fields are set,
1670 they will be included in the response, even if the value is the same
1671 as the default.
1673 When `True`, default values are omitted from the response.
1675 Read more about it in the
1676 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
1677 """
1678 ),
1679 ] = False,
1680 response_model_exclude_defaults: Annotated[
1681 bool,
1682 Doc(
1683 """
1684 Configuration passed to Pydantic to define if the response data
1685 should have all the fields, including the ones that have the same value
1686 as the default. This is different from `response_model_exclude_unset`
1687 in that if the fields are set but contain the same default values,
1688 they will be excluded from the response.
1690 When `True`, default values are omitted from the response.
1692 Read more about it in the
1693 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
1694 """
1695 ),
1696 ] = False,
1697 response_model_exclude_none: Annotated[
1698 bool,
1699 Doc(
1700 """
1701 Configuration passed to Pydantic to define if the response data should
1702 exclude fields set to `None`.
1704 This is much simpler (less smart) than `response_model_exclude_unset`
1705 and `response_model_exclude_defaults`. You probably want to use one of
1706 those two instead of this one, as those allow returning `None` values
1707 when it makes sense.
1709 Read more about it in the
1710 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
1711 """
1712 ),
1713 ] = False,
1714 include_in_schema: Annotated[
1715 bool,
1716 Doc(
1717 """
1718 Include this *path operation* in the generated OpenAPI schema.
1720 This affects the generated OpenAPI (e.g. visible at `/docs`).
1722 Read more about it in the
1723 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
1724 """
1725 ),
1726 ] = True,
1727 response_class: Annotated[
1728 Type[Response],
1729 Doc(
1730 """
1731 Response class to be used for this *path operation*.
1733 This will not be used if you return a response directly.
1735 Read more about it in the
1736 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
1737 """
1738 ),
1739 ] = Default(JSONResponse),
1740 name: Annotated[
1741 Optional[str],
1742 Doc(
1743 """
1744 Name for this *path operation*. Only used internally.
1745 """
1746 ),
1747 ] = None,
1748 callbacks: Annotated[
1749 Optional[List[BaseRoute]],
1750 Doc(
1751 """
1752 List of *path operations* that will be used as OpenAPI callbacks.
1754 This is only for OpenAPI documentation, the callbacks won't be used
1755 directly.
1757 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1759 Read more about it in the
1760 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
1761 """
1762 ),
1763 ] = None,
1764 openapi_extra: Annotated[
1765 Optional[Dict[str, Any]],
1766 Doc(
1767 """
1768 Extra metadata to be included in the OpenAPI schema for this *path
1769 operation*.
1771 Read more about it in the
1772 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
1773 """
1774 ),
1775 ] = None,
1776 generate_unique_id_function: Annotated[
1777 Callable[[routing.APIRoute], str],
1778 Doc(
1779 """
1780 Customize the function used to generate unique IDs for the *path
1781 operations* shown in the generated OpenAPI.
1783 This is particularly useful when automatically generating clients or
1784 SDKs for your API.
1786 Read more about it in the
1787 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1788 """
1789 ),
1790 ] = Default(generate_unique_id),
1791 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
1792 """
1793 Add a *path operation* using an HTTP GET operation.
1795 ## Example
1797 ```python
1798 from fastapi import FastAPI
1800 app = FastAPI()
1802 @app.get("/items/")
1803 def read_items():
1804 return [{"name": "Empanada"}, {"name": "Arepa"}]
1805 ```
1806 """
1807 return self.router.get( 1abcde
1808 path,
1809 response_model=response_model,
1810 status_code=status_code,
1811 tags=tags,
1812 dependencies=dependencies,
1813 summary=summary,
1814 description=description,
1815 response_description=response_description,
1816 responses=responses,
1817 deprecated=deprecated,
1818 operation_id=operation_id,
1819 response_model_include=response_model_include,
1820 response_model_exclude=response_model_exclude,
1821 response_model_by_alias=response_model_by_alias,
1822 response_model_exclude_unset=response_model_exclude_unset,
1823 response_model_exclude_defaults=response_model_exclude_defaults,
1824 response_model_exclude_none=response_model_exclude_none,
1825 include_in_schema=include_in_schema,
1826 response_class=response_class,
1827 name=name,
1828 callbacks=callbacks,
1829 openapi_extra=openapi_extra,
1830 generate_unique_id_function=generate_unique_id_function,
1831 )
1833 def put( 1abcde
1834 self,
1835 path: Annotated[
1836 str,
1837 Doc(
1838 """
1839 The URL path to be used for this *path operation*.
1841 For example, in `http://example.com/items`, the path is `/items`.
1842 """
1843 ),
1844 ],
1845 *,
1846 response_model: Annotated[
1847 Any,
1848 Doc(
1849 """
1850 The type to use for the response.
1852 It could be any valid Pydantic *field* type. So, it doesn't have to
1853 be a Pydantic model, it could be other things, like a `list`, `dict`,
1854 etc.
1856 It will be used for:
1858 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
1859 show it as the response (JSON Schema).
1860 * Serialization: you could return an arbitrary object and the
1861 `response_model` would be used to serialize that object into the
1862 corresponding JSON.
1863 * Filtering: the JSON sent to the client will only contain the data
1864 (fields) defined in the `response_model`. If you returned an object
1865 that contains an attribute `password` but the `response_model` does
1866 not include that field, the JSON sent to the client would not have
1867 that `password`.
1868 * Validation: whatever you return will be serialized with the
1869 `response_model`, converting any data as necessary to generate the
1870 corresponding JSON. But if the data in the object returned is not
1871 valid, that would mean a violation of the contract with the client,
1872 so it's an error from the API developer. So, FastAPI will raise an
1873 error and return a 500 error code (Internal Server Error).
1875 Read more about it in the
1876 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
1877 """
1878 ),
1879 ] = Default(None),
1880 status_code: Annotated[
1881 Optional[int],
1882 Doc(
1883 """
1884 The default status code to be used for the response.
1886 You could override the status code by returning a response directly.
1888 Read more about it in the
1889 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
1890 """
1891 ),
1892 ] = None,
1893 tags: Annotated[
1894 Optional[List[Union[str, Enum]]],
1895 Doc(
1896 """
1897 A list of tags to be applied to the *path operation*.
1899 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1901 Read more about it in the
1902 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
1903 """
1904 ),
1905 ] = None,
1906 dependencies: Annotated[
1907 Optional[Sequence[Depends]],
1908 Doc(
1909 """
1910 A list of dependencies (using `Depends()`) to be applied to the
1911 *path operation*.
1913 Read more about it in the
1914 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
1915 """
1916 ),
1917 ] = None,
1918 summary: Annotated[
1919 Optional[str],
1920 Doc(
1921 """
1922 A summary for the *path operation*.
1924 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1926 Read more about it in the
1927 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1928 """
1929 ),
1930 ] = None,
1931 description: Annotated[
1932 Optional[str],
1933 Doc(
1934 """
1935 A description for the *path operation*.
1937 If not provided, it will be extracted automatically from the docstring
1938 of the *path operation function*.
1940 It can contain Markdown.
1942 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1944 Read more about it in the
1945 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
1946 """
1947 ),
1948 ] = None,
1949 response_description: Annotated[
1950 str,
1951 Doc(
1952 """
1953 The description for the default response.
1955 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1956 """
1957 ),
1958 ] = "Successful Response",
1959 responses: Annotated[
1960 Optional[Dict[Union[int, str], Dict[str, Any]]],
1961 Doc(
1962 """
1963 Additional responses that could be returned by this *path operation*.
1965 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1966 """
1967 ),
1968 ] = None,
1969 deprecated: Annotated[
1970 Optional[bool],
1971 Doc(
1972 """
1973 Mark this *path operation* as deprecated.
1975 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
1976 """
1977 ),
1978 ] = None,
1979 operation_id: Annotated[
1980 Optional[str],
1981 Doc(
1982 """
1983 Custom operation ID to be used by this *path operation*.
1985 By default, it is generated automatically.
1987 If you provide a custom operation ID, you need to make sure it is
1988 unique for the whole API.
1990 You can customize the
1991 operation ID generation with the parameter
1992 `generate_unique_id_function` in the `FastAPI` class.
1994 Read more about it in the
1995 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
1996 """
1997 ),
1998 ] = None,
1999 response_model_include: Annotated[
2000 Optional[IncEx],
2001 Doc(
2002 """
2003 Configuration passed to Pydantic to include only certain fields in the
2004 response data.
2006 Read more about it in the
2007 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2008 """
2009 ),
2010 ] = None,
2011 response_model_exclude: Annotated[
2012 Optional[IncEx],
2013 Doc(
2014 """
2015 Configuration passed to Pydantic to exclude certain fields in the
2016 response data.
2018 Read more about it in the
2019 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2020 """
2021 ),
2022 ] = None,
2023 response_model_by_alias: Annotated[
2024 bool,
2025 Doc(
2026 """
2027 Configuration passed to Pydantic to define if the response model
2028 should be serialized by alias when an alias is used.
2030 Read more about it in the
2031 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2032 """
2033 ),
2034 ] = True,
2035 response_model_exclude_unset: Annotated[
2036 bool,
2037 Doc(
2038 """
2039 Configuration passed to Pydantic to define if the response data
2040 should have all the fields, including the ones that were not set and
2041 have their default values. This is different from
2042 `response_model_exclude_defaults` in that if the fields are set,
2043 they will be included in the response, even if the value is the same
2044 as the default.
2046 When `True`, default values are omitted from the response.
2048 Read more about it in the
2049 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2050 """
2051 ),
2052 ] = False,
2053 response_model_exclude_defaults: Annotated[
2054 bool,
2055 Doc(
2056 """
2057 Configuration passed to Pydantic to define if the response data
2058 should have all the fields, including the ones that have the same value
2059 as the default. This is different from `response_model_exclude_unset`
2060 in that if the fields are set but contain the same default values,
2061 they will be excluded from the response.
2063 When `True`, default values are omitted from the response.
2065 Read more about it in the
2066 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2067 """
2068 ),
2069 ] = False,
2070 response_model_exclude_none: Annotated[
2071 bool,
2072 Doc(
2073 """
2074 Configuration passed to Pydantic to define if the response data should
2075 exclude fields set to `None`.
2077 This is much simpler (less smart) than `response_model_exclude_unset`
2078 and `response_model_exclude_defaults`. You probably want to use one of
2079 those two instead of this one, as those allow returning `None` values
2080 when it makes sense.
2082 Read more about it in the
2083 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
2084 """
2085 ),
2086 ] = False,
2087 include_in_schema: Annotated[
2088 bool,
2089 Doc(
2090 """
2091 Include this *path operation* in the generated OpenAPI schema.
2093 This affects the generated OpenAPI (e.g. visible at `/docs`).
2095 Read more about it in the
2096 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
2097 """
2098 ),
2099 ] = True,
2100 response_class: Annotated[
2101 Type[Response],
2102 Doc(
2103 """
2104 Response class to be used for this *path operation*.
2106 This will not be used if you return a response directly.
2108 Read more about it in the
2109 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
2110 """
2111 ),
2112 ] = Default(JSONResponse),
2113 name: Annotated[
2114 Optional[str],
2115 Doc(
2116 """
2117 Name for this *path operation*. Only used internally.
2118 """
2119 ),
2120 ] = None,
2121 callbacks: Annotated[
2122 Optional[List[BaseRoute]],
2123 Doc(
2124 """
2125 List of *path operations* that will be used as OpenAPI callbacks.
2127 This is only for OpenAPI documentation, the callbacks won't be used
2128 directly.
2130 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2132 Read more about it in the
2133 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
2134 """
2135 ),
2136 ] = None,
2137 openapi_extra: Annotated[
2138 Optional[Dict[str, Any]],
2139 Doc(
2140 """
2141 Extra metadata to be included in the OpenAPI schema for this *path
2142 operation*.
2144 Read more about it in the
2145 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
2146 """
2147 ),
2148 ] = None,
2149 generate_unique_id_function: Annotated[
2150 Callable[[routing.APIRoute], str],
2151 Doc(
2152 """
2153 Customize the function used to generate unique IDs for the *path
2154 operations* shown in the generated OpenAPI.
2156 This is particularly useful when automatically generating clients or
2157 SDKs for your API.
2159 Read more about it in the
2160 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2161 """
2162 ),
2163 ] = Default(generate_unique_id),
2164 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
2165 """
2166 Add a *path operation* using an HTTP PUT operation.
2168 ## Example
2170 ```python
2171 from fastapi import FastAPI
2172 from pydantic import BaseModel
2174 class Item(BaseModel):
2175 name: str
2176 description: str | None = None
2178 app = FastAPI()
2180 @app.put("/items/{item_id}")
2181 def replace_item(item_id: str, item: Item):
2182 return {"message": "Item replaced", "id": item_id}
2183 ```
2184 """
2185 return self.router.put( 1abcde
2186 path,
2187 response_model=response_model,
2188 status_code=status_code,
2189 tags=tags,
2190 dependencies=dependencies,
2191 summary=summary,
2192 description=description,
2193 response_description=response_description,
2194 responses=responses,
2195 deprecated=deprecated,
2196 operation_id=operation_id,
2197 response_model_include=response_model_include,
2198 response_model_exclude=response_model_exclude,
2199 response_model_by_alias=response_model_by_alias,
2200 response_model_exclude_unset=response_model_exclude_unset,
2201 response_model_exclude_defaults=response_model_exclude_defaults,
2202 response_model_exclude_none=response_model_exclude_none,
2203 include_in_schema=include_in_schema,
2204 response_class=response_class,
2205 name=name,
2206 callbacks=callbacks,
2207 openapi_extra=openapi_extra,
2208 generate_unique_id_function=generate_unique_id_function,
2209 )
2211 def post( 1abcde
2212 self,
2213 path: Annotated[
2214 str,
2215 Doc(
2216 """
2217 The URL path to be used for this *path operation*.
2219 For example, in `http://example.com/items`, the path is `/items`.
2220 """
2221 ),
2222 ],
2223 *,
2224 response_model: Annotated[
2225 Any,
2226 Doc(
2227 """
2228 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.
2234 It will be used for:
2236 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
2237 show it as the response (JSON Schema).
2238 * Serialization: you could return an arbitrary object and the
2239 `response_model` would be used to serialize that object into the
2240 corresponding JSON.
2241 * Filtering: the JSON sent to the client will only contain the data
2242 (fields) defined in the `response_model`. If you returned an object
2243 that contains an attribute `password` but the `response_model` does
2244 not include that field, the JSON sent to the client would not have
2245 that `password`.
2246 * Validation: whatever you return will be serialized with the
2247 `response_model`, converting any data as necessary to generate the
2248 corresponding JSON. But if the data in the object returned is not
2249 valid, that would mean a violation of the contract with the client,
2250 so it's an error from the API developer. So, FastAPI will raise an
2251 error and return a 500 error code (Internal Server Error).
2253 Read more about it in the
2254 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
2255 """
2256 ),
2257 ] = Default(None),
2258 status_code: Annotated[
2259 Optional[int],
2260 Doc(
2261 """
2262 The default status code to be used for the response.
2264 You could override the status code by returning a response directly.
2266 Read more about it in the
2267 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
2268 """
2269 ),
2270 ] = None,
2271 tags: Annotated[
2272 Optional[List[Union[str, Enum]]],
2273 Doc(
2274 """
2275 A list of tags to be applied to the *path operation*.
2277 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2279 Read more about it in the
2280 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
2281 """
2282 ),
2283 ] = None,
2284 dependencies: Annotated[
2285 Optional[Sequence[Depends]],
2286 Doc(
2287 """
2288 A list of dependencies (using `Depends()`) to be applied to the
2289 *path operation*.
2291 Read more about it in the
2292 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
2293 """
2294 ),
2295 ] = None,
2296 summary: Annotated[
2297 Optional[str],
2298 Doc(
2299 """
2300 A summary for the *path operation*.
2302 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2304 Read more about it in the
2305 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2306 """
2307 ),
2308 ] = None,
2309 description: Annotated[
2310 Optional[str],
2311 Doc(
2312 """
2313 A description for the *path operation*.
2315 If not provided, it will be extracted automatically from the docstring
2316 of the *path operation function*.
2318 It can contain Markdown.
2320 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2322 Read more about it in the
2323 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2324 """
2325 ),
2326 ] = None,
2327 response_description: Annotated[
2328 str,
2329 Doc(
2330 """
2331 The description for the default response.
2333 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2334 """
2335 ),
2336 ] = "Successful Response",
2337 responses: Annotated[
2338 Optional[Dict[Union[int, str], Dict[str, Any]]],
2339 Doc(
2340 """
2341 Additional responses that could be returned by this *path operation*.
2343 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2344 """
2345 ),
2346 ] = None,
2347 deprecated: Annotated[
2348 Optional[bool],
2349 Doc(
2350 """
2351 Mark this *path operation* as deprecated.
2353 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2354 """
2355 ),
2356 ] = None,
2357 operation_id: Annotated[
2358 Optional[str],
2359 Doc(
2360 """
2361 Custom operation ID to be used by this *path operation*.
2363 By default, it is generated automatically.
2365 If you provide a custom operation ID, you need to make sure it is
2366 unique for the whole API.
2368 You can customize the
2369 operation ID generation with the parameter
2370 `generate_unique_id_function` in the `FastAPI` class.
2372 Read more about it in the
2373 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2374 """
2375 ),
2376 ] = None,
2377 response_model_include: Annotated[
2378 Optional[IncEx],
2379 Doc(
2380 """
2381 Configuration passed to Pydantic to include only certain fields in the
2382 response data.
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 ] = None,
2389 response_model_exclude: Annotated[
2390 Optional[IncEx],
2391 Doc(
2392 """
2393 Configuration passed to Pydantic to exclude certain fields in the
2394 response data.
2396 Read more about it in the
2397 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2398 """
2399 ),
2400 ] = None,
2401 response_model_by_alias: Annotated[
2402 bool,
2403 Doc(
2404 """
2405 Configuration passed to Pydantic to define if the response model
2406 should be serialized by alias when an alias is used.
2408 Read more about it in the
2409 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2410 """
2411 ),
2412 ] = True,
2413 response_model_exclude_unset: Annotated[
2414 bool,
2415 Doc(
2416 """
2417 Configuration passed to Pydantic to define if the response data
2418 should have all the fields, including the ones that were not set and
2419 have their default values. This is different from
2420 `response_model_exclude_defaults` in that if the fields are set,
2421 they will be included in the response, even if the value is the same
2422 as the default.
2424 When `True`, default values are omitted from the response.
2426 Read more about it in the
2427 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2428 """
2429 ),
2430 ] = False,
2431 response_model_exclude_defaults: Annotated[
2432 bool,
2433 Doc(
2434 """
2435 Configuration passed to Pydantic to define if the response data
2436 should have all the fields, including the ones that have the same value
2437 as the default. This is different from `response_model_exclude_unset`
2438 in that if the fields are set but contain the same default values,
2439 they will be excluded from the response.
2441 When `True`, default values are omitted from the response.
2443 Read more about it in the
2444 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2445 """
2446 ),
2447 ] = False,
2448 response_model_exclude_none: Annotated[
2449 bool,
2450 Doc(
2451 """
2452 Configuration passed to Pydantic to define if the response data should
2453 exclude fields set to `None`.
2455 This is much simpler (less smart) than `response_model_exclude_unset`
2456 and `response_model_exclude_defaults`. You probably want to use one of
2457 those two instead of this one, as those allow returning `None` values
2458 when it makes sense.
2460 Read more about it in the
2461 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
2462 """
2463 ),
2464 ] = False,
2465 include_in_schema: Annotated[
2466 bool,
2467 Doc(
2468 """
2469 Include this *path operation* in the generated OpenAPI schema.
2471 This affects the generated OpenAPI (e.g. visible at `/docs`).
2473 Read more about it in the
2474 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
2475 """
2476 ),
2477 ] = True,
2478 response_class: Annotated[
2479 Type[Response],
2480 Doc(
2481 """
2482 Response class to be used for this *path operation*.
2484 This will not be used if you return a response directly.
2486 Read more about it in the
2487 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
2488 """
2489 ),
2490 ] = Default(JSONResponse),
2491 name: Annotated[
2492 Optional[str],
2493 Doc(
2494 """
2495 Name for this *path operation*. Only used internally.
2496 """
2497 ),
2498 ] = None,
2499 callbacks: Annotated[
2500 Optional[List[BaseRoute]],
2501 Doc(
2502 """
2503 List of *path operations* that will be used as OpenAPI callbacks.
2505 This is only for OpenAPI documentation, the callbacks won't be used
2506 directly.
2508 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2510 Read more about it in the
2511 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
2512 """
2513 ),
2514 ] = None,
2515 openapi_extra: Annotated[
2516 Optional[Dict[str, Any]],
2517 Doc(
2518 """
2519 Extra metadata to be included in the OpenAPI schema for this *path
2520 operation*.
2522 Read more about it in the
2523 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
2524 """
2525 ),
2526 ] = None,
2527 generate_unique_id_function: Annotated[
2528 Callable[[routing.APIRoute], str],
2529 Doc(
2530 """
2531 Customize the function used to generate unique IDs for the *path
2532 operations* shown in the generated OpenAPI.
2534 This is particularly useful when automatically generating clients or
2535 SDKs for your API.
2537 Read more about it in the
2538 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2539 """
2540 ),
2541 ] = Default(generate_unique_id),
2542 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
2543 """
2544 Add a *path operation* using an HTTP POST operation.
2546 ## Example
2548 ```python
2549 from fastapi import FastAPI
2550 from pydantic import BaseModel
2552 class Item(BaseModel):
2553 name: str
2554 description: str | None = None
2556 app = FastAPI()
2558 @app.post("/items/")
2559 def create_item(item: Item):
2560 return {"message": "Item created"}
2561 ```
2562 """
2563 return self.router.post( 1abcde
2564 path,
2565 response_model=response_model,
2566 status_code=status_code,
2567 tags=tags,
2568 dependencies=dependencies,
2569 summary=summary,
2570 description=description,
2571 response_description=response_description,
2572 responses=responses,
2573 deprecated=deprecated,
2574 operation_id=operation_id,
2575 response_model_include=response_model_include,
2576 response_model_exclude=response_model_exclude,
2577 response_model_by_alias=response_model_by_alias,
2578 response_model_exclude_unset=response_model_exclude_unset,
2579 response_model_exclude_defaults=response_model_exclude_defaults,
2580 response_model_exclude_none=response_model_exclude_none,
2581 include_in_schema=include_in_schema,
2582 response_class=response_class,
2583 name=name,
2584 callbacks=callbacks,
2585 openapi_extra=openapi_extra,
2586 generate_unique_id_function=generate_unique_id_function,
2587 )
2589 def delete( 1abcde
2590 self,
2591 path: Annotated[
2592 str,
2593 Doc(
2594 """
2595 The URL path to be used for this *path operation*.
2597 For example, in `http://example.com/items`, the path is `/items`.
2598 """
2599 ),
2600 ],
2601 *,
2602 response_model: Annotated[
2603 Any,
2604 Doc(
2605 """
2606 The type to use for the response.
2608 It could be any valid Pydantic *field* type. So, it doesn't have to
2609 be a Pydantic model, it could be other things, like a `list`, `dict`,
2610 etc.
2612 It will be used for:
2614 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
2615 show it as the response (JSON Schema).
2616 * Serialization: you could return an arbitrary object and the
2617 `response_model` would be used to serialize that object into the
2618 corresponding JSON.
2619 * Filtering: the JSON sent to the client will only contain the data
2620 (fields) defined in the `response_model`. If you returned an object
2621 that contains an attribute `password` but the `response_model` does
2622 not include that field, the JSON sent to the client would not have
2623 that `password`.
2624 * Validation: whatever you return will be serialized with the
2625 `response_model`, converting any data as necessary to generate the
2626 corresponding JSON. But if the data in the object returned is not
2627 valid, that would mean a violation of the contract with the client,
2628 so it's an error from the API developer. So, FastAPI will raise an
2629 error and return a 500 error code (Internal Server Error).
2631 Read more about it in the
2632 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
2633 """
2634 ),
2635 ] = Default(None),
2636 status_code: Annotated[
2637 Optional[int],
2638 Doc(
2639 """
2640 The default status code to be used for the response.
2642 You could override the status code by returning a response directly.
2644 Read more about it in the
2645 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
2646 """
2647 ),
2648 ] = None,
2649 tags: Annotated[
2650 Optional[List[Union[str, Enum]]],
2651 Doc(
2652 """
2653 A list of tags to be applied to the *path operation*.
2655 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2657 Read more about it in the
2658 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
2659 """
2660 ),
2661 ] = None,
2662 dependencies: Annotated[
2663 Optional[Sequence[Depends]],
2664 Doc(
2665 """
2666 A list of dependencies (using `Depends()`) to be applied to the
2667 *path operation*.
2669 Read more about it in the
2670 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
2671 """
2672 ),
2673 ] = None,
2674 summary: Annotated[
2675 Optional[str],
2676 Doc(
2677 """
2678 A summary for the *path operation*.
2680 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2682 Read more about it in the
2683 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2684 """
2685 ),
2686 ] = None,
2687 description: Annotated[
2688 Optional[str],
2689 Doc(
2690 """
2691 A description for the *path operation*.
2693 If not provided, it will be extracted automatically from the docstring
2694 of the *path operation function*.
2696 It can contain Markdown.
2698 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2700 Read more about it in the
2701 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
2702 """
2703 ),
2704 ] = None,
2705 response_description: Annotated[
2706 str,
2707 Doc(
2708 """
2709 The description for the default response.
2711 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2712 """
2713 ),
2714 ] = "Successful Response",
2715 responses: Annotated[
2716 Optional[Dict[Union[int, str], Dict[str, Any]]],
2717 Doc(
2718 """
2719 Additional responses that could be returned by this *path operation*.
2721 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2722 """
2723 ),
2724 ] = None,
2725 deprecated: Annotated[
2726 Optional[bool],
2727 Doc(
2728 """
2729 Mark this *path operation* as deprecated.
2731 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2732 """
2733 ),
2734 ] = None,
2735 operation_id: Annotated[
2736 Optional[str],
2737 Doc(
2738 """
2739 Custom operation ID to be used by this *path operation*.
2741 By default, it is generated automatically.
2743 If you provide a custom operation ID, you need to make sure it is
2744 unique for the whole API.
2746 You can customize the
2747 operation ID generation with the parameter
2748 `generate_unique_id_function` in the `FastAPI` class.
2750 Read more about it in the
2751 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2752 """
2753 ),
2754 ] = None,
2755 response_model_include: Annotated[
2756 Optional[IncEx],
2757 Doc(
2758 """
2759 Configuration passed to Pydantic to include only certain fields in the
2760 response data.
2762 Read more about it in the
2763 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2764 """
2765 ),
2766 ] = None,
2767 response_model_exclude: Annotated[
2768 Optional[IncEx],
2769 Doc(
2770 """
2771 Configuration passed to Pydantic to exclude certain fields in the
2772 response data.
2774 Read more about it in the
2775 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2776 """
2777 ),
2778 ] = None,
2779 response_model_by_alias: Annotated[
2780 bool,
2781 Doc(
2782 """
2783 Configuration passed to Pydantic to define if the response model
2784 should be serialized by alias when an alias is used.
2786 Read more about it in the
2787 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
2788 """
2789 ),
2790 ] = True,
2791 response_model_exclude_unset: Annotated[
2792 bool,
2793 Doc(
2794 """
2795 Configuration passed to Pydantic to define if the response data
2796 should have all the fields, including the ones that were not set and
2797 have their default values. This is different from
2798 `response_model_exclude_defaults` in that if the fields are set,
2799 they will be included in the response, even if the value is the same
2800 as the default.
2802 When `True`, default values are omitted from the response.
2804 Read more about it in the
2805 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2806 """
2807 ),
2808 ] = False,
2809 response_model_exclude_defaults: Annotated[
2810 bool,
2811 Doc(
2812 """
2813 Configuration passed to Pydantic to define if the response data
2814 should have all the fields, including the ones that have the same value
2815 as the default. This is different from `response_model_exclude_unset`
2816 in that if the fields are set but contain the same default values,
2817 they will be excluded from the response.
2819 When `True`, default values are omitted from the response.
2821 Read more about it in the
2822 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
2823 """
2824 ),
2825 ] = False,
2826 response_model_exclude_none: Annotated[
2827 bool,
2828 Doc(
2829 """
2830 Configuration passed to Pydantic to define if the response data should
2831 exclude fields set to `None`.
2833 This is much simpler (less smart) than `response_model_exclude_unset`
2834 and `response_model_exclude_defaults`. You probably want to use one of
2835 those two instead of this one, as those allow returning `None` values
2836 when it makes sense.
2838 Read more about it in the
2839 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
2840 """
2841 ),
2842 ] = False,
2843 include_in_schema: Annotated[
2844 bool,
2845 Doc(
2846 """
2847 Include this *path operation* in the generated OpenAPI schema.
2849 This affects the generated OpenAPI (e.g. visible at `/docs`).
2851 Read more about it in the
2852 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
2853 """
2854 ),
2855 ] = True,
2856 response_class: Annotated[
2857 Type[Response],
2858 Doc(
2859 """
2860 Response class to be used for this *path operation*.
2862 This will not be used if you return a response directly.
2864 Read more about it in the
2865 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
2866 """
2867 ),
2868 ] = Default(JSONResponse),
2869 name: Annotated[
2870 Optional[str],
2871 Doc(
2872 """
2873 Name for this *path operation*. Only used internally.
2874 """
2875 ),
2876 ] = None,
2877 callbacks: Annotated[
2878 Optional[List[BaseRoute]],
2879 Doc(
2880 """
2881 List of *path operations* that will be used as OpenAPI callbacks.
2883 This is only for OpenAPI documentation, the callbacks won't be used
2884 directly.
2886 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
2888 Read more about it in the
2889 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
2890 """
2891 ),
2892 ] = None,
2893 openapi_extra: Annotated[
2894 Optional[Dict[str, Any]],
2895 Doc(
2896 """
2897 Extra metadata to be included in the OpenAPI schema for this *path
2898 operation*.
2900 Read more about it in the
2901 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
2902 """
2903 ),
2904 ] = None,
2905 generate_unique_id_function: Annotated[
2906 Callable[[routing.APIRoute], str],
2907 Doc(
2908 """
2909 Customize the function used to generate unique IDs for the *path
2910 operations* shown in the generated OpenAPI.
2912 This is particularly useful when automatically generating clients or
2913 SDKs for your API.
2915 Read more about it in the
2916 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
2917 """
2918 ),
2919 ] = Default(generate_unique_id),
2920 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
2921 """
2922 Add a *path operation* using an HTTP DELETE operation.
2924 ## Example
2926 ```python
2927 from fastapi import FastAPI
2929 app = FastAPI()
2931 @app.delete("/items/{item_id}")
2932 def delete_item(item_id: str):
2933 return {"message": "Item deleted"}
2934 ```
2935 """
2936 return self.router.delete( 1abcde
2937 path,
2938 response_model=response_model,
2939 status_code=status_code,
2940 tags=tags,
2941 dependencies=dependencies,
2942 summary=summary,
2943 description=description,
2944 response_description=response_description,
2945 responses=responses,
2946 deprecated=deprecated,
2947 operation_id=operation_id,
2948 response_model_include=response_model_include,
2949 response_model_exclude=response_model_exclude,
2950 response_model_by_alias=response_model_by_alias,
2951 response_model_exclude_unset=response_model_exclude_unset,
2952 response_model_exclude_defaults=response_model_exclude_defaults,
2953 response_model_exclude_none=response_model_exclude_none,
2954 include_in_schema=include_in_schema,
2955 response_class=response_class,
2956 name=name,
2957 callbacks=callbacks,
2958 openapi_extra=openapi_extra,
2959 generate_unique_id_function=generate_unique_id_function,
2960 )
2962 def options( 1abcde
2963 self,
2964 path: Annotated[
2965 str,
2966 Doc(
2967 """
2968 The URL path to be used for this *path operation*.
2970 For example, in `http://example.com/items`, the path is `/items`.
2971 """
2972 ),
2973 ],
2974 *,
2975 response_model: Annotated[
2976 Any,
2977 Doc(
2978 """
2979 The type to use for the response.
2981 It could be any valid Pydantic *field* type. So, it doesn't have to
2982 be a Pydantic model, it could be other things, like a `list`, `dict`,
2983 etc.
2985 It will be used for:
2987 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
2988 show it as the response (JSON Schema).
2989 * Serialization: you could return an arbitrary object and the
2990 `response_model` would be used to serialize that object into the
2991 corresponding JSON.
2992 * Filtering: the JSON sent to the client will only contain the data
2993 (fields) defined in the `response_model`. If you returned an object
2994 that contains an attribute `password` but the `response_model` does
2995 not include that field, the JSON sent to the client would not have
2996 that `password`.
2997 * Validation: whatever you return will be serialized with the
2998 `response_model`, converting any data as necessary to generate the
2999 corresponding JSON. But if the data in the object returned is not
3000 valid, that would mean a violation of the contract with the client,
3001 so it's an error from the API developer. So, FastAPI will raise an
3002 error and return a 500 error code (Internal Server Error).
3004 Read more about it in the
3005 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
3006 """
3007 ),
3008 ] = Default(None),
3009 status_code: Annotated[
3010 Optional[int],
3011 Doc(
3012 """
3013 The default status code to be used for the response.
3015 You could override the status code by returning a response directly.
3017 Read more about it in the
3018 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
3019 """
3020 ),
3021 ] = None,
3022 tags: Annotated[
3023 Optional[List[Union[str, Enum]]],
3024 Doc(
3025 """
3026 A list of tags to be applied to the *path operation*.
3028 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3030 Read more about it in the
3031 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
3032 """
3033 ),
3034 ] = None,
3035 dependencies: Annotated[
3036 Optional[Sequence[Depends]],
3037 Doc(
3038 """
3039 A list of dependencies (using `Depends()`) to be applied to the
3040 *path operation*.
3042 Read more about it in the
3043 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
3044 """
3045 ),
3046 ] = None,
3047 summary: Annotated[
3048 Optional[str],
3049 Doc(
3050 """
3051 A summary for the *path operation*.
3053 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3055 Read more about it in the
3056 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3057 """
3058 ),
3059 ] = None,
3060 description: Annotated[
3061 Optional[str],
3062 Doc(
3063 """
3064 A description for the *path operation*.
3066 If not provided, it will be extracted automatically from the docstring
3067 of the *path operation function*.
3069 It can contain Markdown.
3071 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3073 Read more about it in the
3074 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3075 """
3076 ),
3077 ] = None,
3078 response_description: Annotated[
3079 str,
3080 Doc(
3081 """
3082 The description for the default response.
3084 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3085 """
3086 ),
3087 ] = "Successful Response",
3088 responses: Annotated[
3089 Optional[Dict[Union[int, str], Dict[str, Any]]],
3090 Doc(
3091 """
3092 Additional responses that could be returned by this *path operation*.
3094 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3095 """
3096 ),
3097 ] = None,
3098 deprecated: Annotated[
3099 Optional[bool],
3100 Doc(
3101 """
3102 Mark this *path operation* as deprecated.
3104 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3105 """
3106 ),
3107 ] = None,
3108 operation_id: Annotated[
3109 Optional[str],
3110 Doc(
3111 """
3112 Custom operation ID to be used by this *path operation*.
3114 By default, it is generated automatically.
3116 If you provide a custom operation ID, you need to make sure it is
3117 unique for the whole API.
3119 You can customize the
3120 operation ID generation with the parameter
3121 `generate_unique_id_function` in the `FastAPI` class.
3123 Read more about it in the
3124 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3125 """
3126 ),
3127 ] = None,
3128 response_model_include: Annotated[
3129 Optional[IncEx],
3130 Doc(
3131 """
3132 Configuration passed to Pydantic to include only certain fields in the
3133 response data.
3135 Read more about it in the
3136 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3137 """
3138 ),
3139 ] = None,
3140 response_model_exclude: Annotated[
3141 Optional[IncEx],
3142 Doc(
3143 """
3144 Configuration passed to Pydantic to exclude certain fields in the
3145 response data.
3147 Read more about it in the
3148 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3149 """
3150 ),
3151 ] = None,
3152 response_model_by_alias: Annotated[
3153 bool,
3154 Doc(
3155 """
3156 Configuration passed to Pydantic to define if the response model
3157 should be serialized by alias when an alias is used.
3159 Read more about it in the
3160 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3161 """
3162 ),
3163 ] = True,
3164 response_model_exclude_unset: Annotated[
3165 bool,
3166 Doc(
3167 """
3168 Configuration passed to Pydantic to define if the response data
3169 should have all the fields, including the ones that were not set and
3170 have their default values. This is different from
3171 `response_model_exclude_defaults` in that if the fields are set,
3172 they will be included in the response, even if the value is the same
3173 as the default.
3175 When `True`, default values are omitted from the response.
3177 Read more about it in the
3178 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3179 """
3180 ),
3181 ] = False,
3182 response_model_exclude_defaults: Annotated[
3183 bool,
3184 Doc(
3185 """
3186 Configuration passed to Pydantic to define if the response data
3187 should have all the fields, including the ones that have the same value
3188 as the default. This is different from `response_model_exclude_unset`
3189 in that if the fields are set but contain the same default values,
3190 they will be excluded from the response.
3192 When `True`, default values are omitted from the response.
3194 Read more about it in the
3195 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3196 """
3197 ),
3198 ] = False,
3199 response_model_exclude_none: Annotated[
3200 bool,
3201 Doc(
3202 """
3203 Configuration passed to Pydantic to define if the response data should
3204 exclude fields set to `None`.
3206 This is much simpler (less smart) than `response_model_exclude_unset`
3207 and `response_model_exclude_defaults`. You probably want to use one of
3208 those two instead of this one, as those allow returning `None` values
3209 when it makes sense.
3211 Read more about it in the
3212 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
3213 """
3214 ),
3215 ] = False,
3216 include_in_schema: Annotated[
3217 bool,
3218 Doc(
3219 """
3220 Include this *path operation* in the generated OpenAPI schema.
3222 This affects the generated OpenAPI (e.g. visible at `/docs`).
3224 Read more about it in the
3225 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
3226 """
3227 ),
3228 ] = True,
3229 response_class: Annotated[
3230 Type[Response],
3231 Doc(
3232 """
3233 Response class to be used for this *path operation*.
3235 This will not be used if you return a response directly.
3237 Read more about it in the
3238 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
3239 """
3240 ),
3241 ] = Default(JSONResponse),
3242 name: Annotated[
3243 Optional[str],
3244 Doc(
3245 """
3246 Name for this *path operation*. Only used internally.
3247 """
3248 ),
3249 ] = None,
3250 callbacks: Annotated[
3251 Optional[List[BaseRoute]],
3252 Doc(
3253 """
3254 List of *path operations* that will be used as OpenAPI callbacks.
3256 This is only for OpenAPI documentation, the callbacks won't be used
3257 directly.
3259 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3261 Read more about it in the
3262 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
3263 """
3264 ),
3265 ] = None,
3266 openapi_extra: Annotated[
3267 Optional[Dict[str, Any]],
3268 Doc(
3269 """
3270 Extra metadata to be included in the OpenAPI schema for this *path
3271 operation*.
3273 Read more about it in the
3274 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
3275 """
3276 ),
3277 ] = None,
3278 generate_unique_id_function: Annotated[
3279 Callable[[routing.APIRoute], str],
3280 Doc(
3281 """
3282 Customize the function used to generate unique IDs for the *path
3283 operations* shown in the generated OpenAPI.
3285 This is particularly useful when automatically generating clients or
3286 SDKs for your API.
3288 Read more about it in the
3289 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3290 """
3291 ),
3292 ] = Default(generate_unique_id),
3293 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
3294 """
3295 Add a *path operation* using an HTTP OPTIONS operation.
3297 ## Example
3299 ```python
3300 from fastapi import FastAPI
3302 app = FastAPI()
3304 @app.options("/items/")
3305 def get_item_options():
3306 return {"additions": ["Aji", "Guacamole"]}
3307 ```
3308 """
3309 return self.router.options( 1abcde
3310 path,
3311 response_model=response_model,
3312 status_code=status_code,
3313 tags=tags,
3314 dependencies=dependencies,
3315 summary=summary,
3316 description=description,
3317 response_description=response_description,
3318 responses=responses,
3319 deprecated=deprecated,
3320 operation_id=operation_id,
3321 response_model_include=response_model_include,
3322 response_model_exclude=response_model_exclude,
3323 response_model_by_alias=response_model_by_alias,
3324 response_model_exclude_unset=response_model_exclude_unset,
3325 response_model_exclude_defaults=response_model_exclude_defaults,
3326 response_model_exclude_none=response_model_exclude_none,
3327 include_in_schema=include_in_schema,
3328 response_class=response_class,
3329 name=name,
3330 callbacks=callbacks,
3331 openapi_extra=openapi_extra,
3332 generate_unique_id_function=generate_unique_id_function,
3333 )
3335 def head( 1abcde
3336 self,
3337 path: Annotated[
3338 str,
3339 Doc(
3340 """
3341 The URL path to be used for this *path operation*.
3343 For example, in `http://example.com/items`, the path is `/items`.
3344 """
3345 ),
3346 ],
3347 *,
3348 response_model: Annotated[
3349 Any,
3350 Doc(
3351 """
3352 The type to use for the response.
3354 It could be any valid Pydantic *field* type. So, it doesn't have to
3355 be a Pydantic model, it could be other things, like a `list`, `dict`,
3356 etc.
3358 It will be used for:
3360 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
3361 show it as the response (JSON Schema).
3362 * Serialization: you could return an arbitrary object and the
3363 `response_model` would be used to serialize that object into the
3364 corresponding JSON.
3365 * Filtering: the JSON sent to the client will only contain the data
3366 (fields) defined in the `response_model`. If you returned an object
3367 that contains an attribute `password` but the `response_model` does
3368 not include that field, the JSON sent to the client would not have
3369 that `password`.
3370 * Validation: whatever you return will be serialized with the
3371 `response_model`, converting any data as necessary to generate the
3372 corresponding JSON. But if the data in the object returned is not
3373 valid, that would mean a violation of the contract with the client,
3374 so it's an error from the API developer. So, FastAPI will raise an
3375 error and return a 500 error code (Internal Server Error).
3377 Read more about it in the
3378 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
3379 """
3380 ),
3381 ] = Default(None),
3382 status_code: Annotated[
3383 Optional[int],
3384 Doc(
3385 """
3386 The default status code to be used for the response.
3388 You could override the status code by returning a response directly.
3390 Read more about it in the
3391 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
3392 """
3393 ),
3394 ] = None,
3395 tags: Annotated[
3396 Optional[List[Union[str, Enum]]],
3397 Doc(
3398 """
3399 A list of tags to be applied to the *path operation*.
3401 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3403 Read more about it in the
3404 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
3405 """
3406 ),
3407 ] = None,
3408 dependencies: Annotated[
3409 Optional[Sequence[Depends]],
3410 Doc(
3411 """
3412 A list of dependencies (using `Depends()`) to be applied to the
3413 *path operation*.
3415 Read more about it in the
3416 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
3417 """
3418 ),
3419 ] = None,
3420 summary: Annotated[
3421 Optional[str],
3422 Doc(
3423 """
3424 A summary for the *path operation*.
3426 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3428 Read more about it in the
3429 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3430 """
3431 ),
3432 ] = None,
3433 description: Annotated[
3434 Optional[str],
3435 Doc(
3436 """
3437 A description for the *path operation*.
3439 If not provided, it will be extracted automatically from the docstring
3440 of the *path operation function*.
3442 It can contain Markdown.
3444 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3446 Read more about it in the
3447 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3448 """
3449 ),
3450 ] = None,
3451 response_description: Annotated[
3452 str,
3453 Doc(
3454 """
3455 The description for the default response.
3457 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3458 """
3459 ),
3460 ] = "Successful Response",
3461 responses: Annotated[
3462 Optional[Dict[Union[int, str], Dict[str, Any]]],
3463 Doc(
3464 """
3465 Additional responses that could be returned by this *path operation*.
3467 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3468 """
3469 ),
3470 ] = None,
3471 deprecated: Annotated[
3472 Optional[bool],
3473 Doc(
3474 """
3475 Mark this *path operation* as deprecated.
3477 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3478 """
3479 ),
3480 ] = None,
3481 operation_id: Annotated[
3482 Optional[str],
3483 Doc(
3484 """
3485 Custom operation ID to be used by this *path operation*.
3487 By default, it is generated automatically.
3489 If you provide a custom operation ID, you need to make sure it is
3490 unique for the whole API.
3492 You can customize the
3493 operation ID generation with the parameter
3494 `generate_unique_id_function` in the `FastAPI` class.
3496 Read more about it in the
3497 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3498 """
3499 ),
3500 ] = None,
3501 response_model_include: Annotated[
3502 Optional[IncEx],
3503 Doc(
3504 """
3505 Configuration passed to Pydantic to include only certain fields in the
3506 response data.
3508 Read more about it in the
3509 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3510 """
3511 ),
3512 ] = None,
3513 response_model_exclude: Annotated[
3514 Optional[IncEx],
3515 Doc(
3516 """
3517 Configuration passed to Pydantic to exclude certain fields in the
3518 response data.
3520 Read more about it in the
3521 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3522 """
3523 ),
3524 ] = None,
3525 response_model_by_alias: Annotated[
3526 bool,
3527 Doc(
3528 """
3529 Configuration passed to Pydantic to define if the response model
3530 should be serialized by alias when an alias is used.
3532 Read more about it in the
3533 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3534 """
3535 ),
3536 ] = True,
3537 response_model_exclude_unset: Annotated[
3538 bool,
3539 Doc(
3540 """
3541 Configuration passed to Pydantic to define if the response data
3542 should have all the fields, including the ones that were not set and
3543 have their default values. This is different from
3544 `response_model_exclude_defaults` in that if the fields are set,
3545 they will be included in the response, even if the value is the same
3546 as the default.
3548 When `True`, default values are omitted from the response.
3550 Read more about it in the
3551 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3552 """
3553 ),
3554 ] = False,
3555 response_model_exclude_defaults: Annotated[
3556 bool,
3557 Doc(
3558 """
3559 Configuration passed to Pydantic to define if the response data
3560 should have all the fields, including the ones that have the same value
3561 as the default. This is different from `response_model_exclude_unset`
3562 in that if the fields are set but contain the same default values,
3563 they will be excluded from the response.
3565 When `True`, default values are omitted from the response.
3567 Read more about it in the
3568 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3569 """
3570 ),
3571 ] = False,
3572 response_model_exclude_none: Annotated[
3573 bool,
3574 Doc(
3575 """
3576 Configuration passed to Pydantic to define if the response data should
3577 exclude fields set to `None`.
3579 This is much simpler (less smart) than `response_model_exclude_unset`
3580 and `response_model_exclude_defaults`. You probably want to use one of
3581 those two instead of this one, as those allow returning `None` values
3582 when it makes sense.
3584 Read more about it in the
3585 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
3586 """
3587 ),
3588 ] = False,
3589 include_in_schema: Annotated[
3590 bool,
3591 Doc(
3592 """
3593 Include this *path operation* in the generated OpenAPI schema.
3595 This affects the generated OpenAPI (e.g. visible at `/docs`).
3597 Read more about it in the
3598 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
3599 """
3600 ),
3601 ] = True,
3602 response_class: Annotated[
3603 Type[Response],
3604 Doc(
3605 """
3606 Response class to be used for this *path operation*.
3608 This will not be used if you return a response directly.
3610 Read more about it in the
3611 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
3612 """
3613 ),
3614 ] = Default(JSONResponse),
3615 name: Annotated[
3616 Optional[str],
3617 Doc(
3618 """
3619 Name for this *path operation*. Only used internally.
3620 """
3621 ),
3622 ] = None,
3623 callbacks: Annotated[
3624 Optional[List[BaseRoute]],
3625 Doc(
3626 """
3627 List of *path operations* that will be used as OpenAPI callbacks.
3629 This is only for OpenAPI documentation, the callbacks won't be used
3630 directly.
3632 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3634 Read more about it in the
3635 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
3636 """
3637 ),
3638 ] = None,
3639 openapi_extra: Annotated[
3640 Optional[Dict[str, Any]],
3641 Doc(
3642 """
3643 Extra metadata to be included in the OpenAPI schema for this *path
3644 operation*.
3646 Read more about it in the
3647 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
3648 """
3649 ),
3650 ] = None,
3651 generate_unique_id_function: Annotated[
3652 Callable[[routing.APIRoute], str],
3653 Doc(
3654 """
3655 Customize the function used to generate unique IDs for the *path
3656 operations* shown in the generated OpenAPI.
3658 This is particularly useful when automatically generating clients or
3659 SDKs for your API.
3661 Read more about it in the
3662 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3663 """
3664 ),
3665 ] = Default(generate_unique_id),
3666 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
3667 """
3668 Add a *path operation* using an HTTP HEAD operation.
3670 ## Example
3672 ```python
3673 from fastapi import FastAPI, Response
3675 app = FastAPI()
3677 @app.head("/items/", status_code=204)
3678 def get_items_headers(response: Response):
3679 response.headers["X-Cat-Dog"] = "Alone in the world"
3680 ```
3681 """
3682 return self.router.head( 1abcde
3683 path,
3684 response_model=response_model,
3685 status_code=status_code,
3686 tags=tags,
3687 dependencies=dependencies,
3688 summary=summary,
3689 description=description,
3690 response_description=response_description,
3691 responses=responses,
3692 deprecated=deprecated,
3693 operation_id=operation_id,
3694 response_model_include=response_model_include,
3695 response_model_exclude=response_model_exclude,
3696 response_model_by_alias=response_model_by_alias,
3697 response_model_exclude_unset=response_model_exclude_unset,
3698 response_model_exclude_defaults=response_model_exclude_defaults,
3699 response_model_exclude_none=response_model_exclude_none,
3700 include_in_schema=include_in_schema,
3701 response_class=response_class,
3702 name=name,
3703 callbacks=callbacks,
3704 openapi_extra=openapi_extra,
3705 generate_unique_id_function=generate_unique_id_function,
3706 )
3708 def patch( 1abcde
3709 self,
3710 path: Annotated[
3711 str,
3712 Doc(
3713 """
3714 The URL path to be used for this *path operation*.
3716 For example, in `http://example.com/items`, the path is `/items`.
3717 """
3718 ),
3719 ],
3720 *,
3721 response_model: Annotated[
3722 Any,
3723 Doc(
3724 """
3725 The type to use for the response.
3727 It could be any valid Pydantic *field* type. So, it doesn't have to
3728 be a Pydantic model, it could be other things, like a `list`, `dict`,
3729 etc.
3731 It will be used for:
3733 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
3734 show it as the response (JSON Schema).
3735 * Serialization: you could return an arbitrary object and the
3736 `response_model` would be used to serialize that object into the
3737 corresponding JSON.
3738 * Filtering: the JSON sent to the client will only contain the data
3739 (fields) defined in the `response_model`. If you returned an object
3740 that contains an attribute `password` but the `response_model` does
3741 not include that field, the JSON sent to the client would not have
3742 that `password`.
3743 * Validation: whatever you return will be serialized with the
3744 `response_model`, converting any data as necessary to generate the
3745 corresponding JSON. But if the data in the object returned is not
3746 valid, that would mean a violation of the contract with the client,
3747 so it's an error from the API developer. So, FastAPI will raise an
3748 error and return a 500 error code (Internal Server Error).
3750 Read more about it in the
3751 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
3752 """
3753 ),
3754 ] = Default(None),
3755 status_code: Annotated[
3756 Optional[int],
3757 Doc(
3758 """
3759 The default status code to be used for the response.
3761 You could override the status code by returning a response directly.
3763 Read more about it in the
3764 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
3765 """
3766 ),
3767 ] = None,
3768 tags: Annotated[
3769 Optional[List[Union[str, Enum]]],
3770 Doc(
3771 """
3772 A list of tags to be applied to the *path operation*.
3774 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3776 Read more about it in the
3777 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
3778 """
3779 ),
3780 ] = None,
3781 dependencies: Annotated[
3782 Optional[Sequence[Depends]],
3783 Doc(
3784 """
3785 A list of dependencies (using `Depends()`) to be applied to the
3786 *path operation*.
3788 Read more about it in the
3789 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
3790 """
3791 ),
3792 ] = None,
3793 summary: Annotated[
3794 Optional[str],
3795 Doc(
3796 """
3797 A summary for the *path operation*.
3799 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3801 Read more about it in the
3802 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3803 """
3804 ),
3805 ] = None,
3806 description: Annotated[
3807 Optional[str],
3808 Doc(
3809 """
3810 A description for the *path operation*.
3812 If not provided, it will be extracted automatically from the docstring
3813 of the *path operation function*.
3815 It can contain Markdown.
3817 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3819 Read more about it in the
3820 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
3821 """
3822 ),
3823 ] = None,
3824 response_description: Annotated[
3825 str,
3826 Doc(
3827 """
3828 The description for the default response.
3830 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3831 """
3832 ),
3833 ] = "Successful Response",
3834 responses: Annotated[
3835 Optional[Dict[Union[int, str], Dict[str, Any]]],
3836 Doc(
3837 """
3838 Additional responses that could be returned by this *path operation*.
3840 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3841 """
3842 ),
3843 ] = None,
3844 deprecated: Annotated[
3845 Optional[bool],
3846 Doc(
3847 """
3848 Mark this *path operation* as deprecated.
3850 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
3851 """
3852 ),
3853 ] = None,
3854 operation_id: Annotated[
3855 Optional[str],
3856 Doc(
3857 """
3858 Custom operation ID to be used by this *path operation*.
3860 By default, it is generated automatically.
3862 If you provide a custom operation ID, you need to make sure it is
3863 unique for the whole API.
3865 You can customize the
3866 operation ID generation with the parameter
3867 `generate_unique_id_function` in the `FastAPI` class.
3869 Read more about it in the
3870 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
3871 """
3872 ),
3873 ] = None,
3874 response_model_include: Annotated[
3875 Optional[IncEx],
3876 Doc(
3877 """
3878 Configuration passed to Pydantic to include only certain fields in the
3879 response data.
3881 Read more about it in the
3882 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3883 """
3884 ),
3885 ] = None,
3886 response_model_exclude: Annotated[
3887 Optional[IncEx],
3888 Doc(
3889 """
3890 Configuration passed to Pydantic to exclude certain fields in the
3891 response data.
3893 Read more about it in the
3894 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3895 """
3896 ),
3897 ] = None,
3898 response_model_by_alias: Annotated[
3899 bool,
3900 Doc(
3901 """
3902 Configuration passed to Pydantic to define if the response model
3903 should be serialized by alias when an alias is used.
3905 Read more about it in the
3906 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
3907 """
3908 ),
3909 ] = True,
3910 response_model_exclude_unset: Annotated[
3911 bool,
3912 Doc(
3913 """
3914 Configuration passed to Pydantic to define if the response data
3915 should have all the fields, including the ones that were not set and
3916 have their default values. This is different from
3917 `response_model_exclude_defaults` in that if the fields are set,
3918 they will be included in the response, even if the value is the same
3919 as the default.
3921 When `True`, default values are omitted from the response.
3923 Read more about it in the
3924 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3925 """
3926 ),
3927 ] = False,
3928 response_model_exclude_defaults: Annotated[
3929 bool,
3930 Doc(
3931 """
3932 Configuration passed to Pydantic to define if the response data
3933 should have all the fields, including the ones that have the same value
3934 as the default. This is different from `response_model_exclude_unset`
3935 in that if the fields are set but contain the same default values,
3936 they will be excluded from the response.
3938 When `True`, default values are omitted from the response.
3940 Read more about it in the
3941 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
3942 """
3943 ),
3944 ] = False,
3945 response_model_exclude_none: Annotated[
3946 bool,
3947 Doc(
3948 """
3949 Configuration passed to Pydantic to define if the response data should
3950 exclude fields set to `None`.
3952 This is much simpler (less smart) than `response_model_exclude_unset`
3953 and `response_model_exclude_defaults`. You probably want to use one of
3954 those two instead of this one, as those allow returning `None` values
3955 when it makes sense.
3957 Read more about it in the
3958 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
3959 """
3960 ),
3961 ] = False,
3962 include_in_schema: Annotated[
3963 bool,
3964 Doc(
3965 """
3966 Include this *path operation* in the generated OpenAPI schema.
3968 This affects the generated OpenAPI (e.g. visible at `/docs`).
3970 Read more about it in the
3971 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
3972 """
3973 ),
3974 ] = True,
3975 response_class: Annotated[
3976 Type[Response],
3977 Doc(
3978 """
3979 Response class to be used for this *path operation*.
3981 This will not be used if you return a response directly.
3983 Read more about it in the
3984 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
3985 """
3986 ),
3987 ] = Default(JSONResponse),
3988 name: Annotated[
3989 Optional[str],
3990 Doc(
3991 """
3992 Name for this *path operation*. Only used internally.
3993 """
3994 ),
3995 ] = None,
3996 callbacks: Annotated[
3997 Optional[List[BaseRoute]],
3998 Doc(
3999 """
4000 List of *path operations* that will be used as OpenAPI callbacks.
4002 This is only for OpenAPI documentation, the callbacks won't be used
4003 directly.
4005 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4007 Read more about it in the
4008 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
4009 """
4010 ),
4011 ] = None,
4012 openapi_extra: Annotated[
4013 Optional[Dict[str, Any]],
4014 Doc(
4015 """
4016 Extra metadata to be included in the OpenAPI schema for this *path
4017 operation*.
4019 Read more about it in the
4020 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
4021 """
4022 ),
4023 ] = None,
4024 generate_unique_id_function: Annotated[
4025 Callable[[routing.APIRoute], str],
4026 Doc(
4027 """
4028 Customize the function used to generate unique IDs for the *path
4029 operations* shown in the generated OpenAPI.
4031 This is particularly useful when automatically generating clients or
4032 SDKs for your API.
4034 Read more about it in the
4035 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
4036 """
4037 ),
4038 ] = Default(generate_unique_id),
4039 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4040 """
4041 Add a *path operation* using an HTTP PATCH operation.
4043 ## Example
4045 ```python
4046 from fastapi import FastAPI
4047 from pydantic import BaseModel
4049 class Item(BaseModel):
4050 name: str
4051 description: str | None = None
4053 app = FastAPI()
4055 @app.patch("/items/")
4056 def update_item(item: Item):
4057 return {"message": "Item updated in place"}
4058 ```
4059 """
4060 return self.router.patch( 1abcde
4061 path,
4062 response_model=response_model,
4063 status_code=status_code,
4064 tags=tags,
4065 dependencies=dependencies,
4066 summary=summary,
4067 description=description,
4068 response_description=response_description,
4069 responses=responses,
4070 deprecated=deprecated,
4071 operation_id=operation_id,
4072 response_model_include=response_model_include,
4073 response_model_exclude=response_model_exclude,
4074 response_model_by_alias=response_model_by_alias,
4075 response_model_exclude_unset=response_model_exclude_unset,
4076 response_model_exclude_defaults=response_model_exclude_defaults,
4077 response_model_exclude_none=response_model_exclude_none,
4078 include_in_schema=include_in_schema,
4079 response_class=response_class,
4080 name=name,
4081 callbacks=callbacks,
4082 openapi_extra=openapi_extra,
4083 generate_unique_id_function=generate_unique_id_function,
4084 )
4086 def trace( 1abcde
4087 self,
4088 path: Annotated[
4089 str,
4090 Doc(
4091 """
4092 The URL path to be used for this *path operation*.
4094 For example, in `http://example.com/items`, the path is `/items`.
4095 """
4096 ),
4097 ],
4098 *,
4099 response_model: Annotated[
4100 Any,
4101 Doc(
4102 """
4103 The type to use for the response.
4105 It could be any valid Pydantic *field* type. So, it doesn't have to
4106 be a Pydantic model, it could be other things, like a `list`, `dict`,
4107 etc.
4109 It will be used for:
4111 * Documentation: the generated OpenAPI (and the UI at `/docs`) will
4112 show it as the response (JSON Schema).
4113 * Serialization: you could return an arbitrary object and the
4114 `response_model` would be used to serialize that object into the
4115 corresponding JSON.
4116 * Filtering: the JSON sent to the client will only contain the data
4117 (fields) defined in the `response_model`. If you returned an object
4118 that contains an attribute `password` but the `response_model` does
4119 not include that field, the JSON sent to the client would not have
4120 that `password`.
4121 * Validation: whatever you return will be serialized with the
4122 `response_model`, converting any data as necessary to generate the
4123 corresponding JSON. But if the data in the object returned is not
4124 valid, that would mean a violation of the contract with the client,
4125 so it's an error from the API developer. So, FastAPI will raise an
4126 error and return a 500 error code (Internal Server Error).
4128 Read more about it in the
4129 [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).
4130 """
4131 ),
4132 ] = Default(None),
4133 status_code: Annotated[
4134 Optional[int],
4135 Doc(
4136 """
4137 The default status code to be used for the response.
4139 You could override the status code by returning a response directly.
4141 Read more about it in the
4142 [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).
4143 """
4144 ),
4145 ] = None,
4146 tags: Annotated[
4147 Optional[List[Union[str, Enum]]],
4148 Doc(
4149 """
4150 A list of tags to be applied to the *path operation*.
4152 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4154 Read more about it in the
4155 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).
4156 """
4157 ),
4158 ] = None,
4159 dependencies: Annotated[
4160 Optional[Sequence[Depends]],
4161 Doc(
4162 """
4163 A list of dependencies (using `Depends()`) to be applied to the
4164 *path operation*.
4166 Read more about it in the
4167 [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).
4168 """
4169 ),
4170 ] = None,
4171 summary: Annotated[
4172 Optional[str],
4173 Doc(
4174 """
4175 A summary for the *path operation*.
4177 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4179 Read more about it in the
4180 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
4181 """
4182 ),
4183 ] = None,
4184 description: Annotated[
4185 Optional[str],
4186 Doc(
4187 """
4188 A description for the *path operation*.
4190 If not provided, it will be extracted automatically from the docstring
4191 of the *path operation function*.
4193 It can contain Markdown.
4195 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4197 Read more about it in the
4198 [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).
4199 """
4200 ),
4201 ] = None,
4202 response_description: Annotated[
4203 str,
4204 Doc(
4205 """
4206 The description for the default response.
4208 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4209 """
4210 ),
4211 ] = "Successful Response",
4212 responses: Annotated[
4213 Optional[Dict[Union[int, str], Dict[str, Any]]],
4214 Doc(
4215 """
4216 Additional responses that could be returned by this *path operation*.
4218 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4219 """
4220 ),
4221 ] = None,
4222 deprecated: Annotated[
4223 Optional[bool],
4224 Doc(
4225 """
4226 Mark this *path operation* as deprecated.
4228 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4229 """
4230 ),
4231 ] = None,
4232 operation_id: Annotated[
4233 Optional[str],
4234 Doc(
4235 """
4236 Custom operation ID to be used by this *path operation*.
4238 By default, it is generated automatically.
4240 If you provide a custom operation ID, you need to make sure it is
4241 unique for the whole API.
4243 You can customize the
4244 operation ID generation with the parameter
4245 `generate_unique_id_function` in the `FastAPI` class.
4247 Read more about it in the
4248 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
4249 """
4250 ),
4251 ] = None,
4252 response_model_include: Annotated[
4253 Optional[IncEx],
4254 Doc(
4255 """
4256 Configuration passed to Pydantic to include only certain fields in the
4257 response data.
4259 Read more about it in the
4260 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
4261 """
4262 ),
4263 ] = None,
4264 response_model_exclude: Annotated[
4265 Optional[IncEx],
4266 Doc(
4267 """
4268 Configuration passed to Pydantic to exclude certain fields in the
4269 response data.
4271 Read more about it in the
4272 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
4273 """
4274 ),
4275 ] = None,
4276 response_model_by_alias: Annotated[
4277 bool,
4278 Doc(
4279 """
4280 Configuration passed to Pydantic to define if the response model
4281 should be serialized by alias when an alias is used.
4283 Read more about it in the
4284 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).
4285 """
4286 ),
4287 ] = True,
4288 response_model_exclude_unset: Annotated[
4289 bool,
4290 Doc(
4291 """
4292 Configuration passed to Pydantic to define if the response data
4293 should have all the fields, including the ones that were not set and
4294 have their default values. This is different from
4295 `response_model_exclude_defaults` in that if the fields are set,
4296 they will be included in the response, even if the value is the same
4297 as the default.
4299 When `True`, default values are omitted from the response.
4301 Read more about it in the
4302 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
4303 """
4304 ),
4305 ] = False,
4306 response_model_exclude_defaults: Annotated[
4307 bool,
4308 Doc(
4309 """
4310 Configuration passed to Pydantic to define if the response data
4311 should have all the fields, including the ones that have the same value
4312 as the default. This is different from `response_model_exclude_unset`
4313 in that if the fields are set but contain the same default values,
4314 they will be excluded from the response.
4316 When `True`, default values are omitted from the response.
4318 Read more about it in the
4319 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).
4320 """
4321 ),
4322 ] = False,
4323 response_model_exclude_none: Annotated[
4324 bool,
4325 Doc(
4326 """
4327 Configuration passed to Pydantic to define if the response data should
4328 exclude fields set to `None`.
4330 This is much simpler (less smart) than `response_model_exclude_unset`
4331 and `response_model_exclude_defaults`. You probably want to use one of
4332 those two instead of this one, as those allow returning `None` values
4333 when it makes sense.
4335 Read more about it in the
4336 [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).
4337 """
4338 ),
4339 ] = False,
4340 include_in_schema: Annotated[
4341 bool,
4342 Doc(
4343 """
4344 Include this *path operation* in the generated OpenAPI schema.
4346 This affects the generated OpenAPI (e.g. visible at `/docs`).
4348 Read more about it in the
4349 [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).
4350 """
4351 ),
4352 ] = True,
4353 response_class: Annotated[
4354 Type[Response],
4355 Doc(
4356 """
4357 Response class to be used for this *path operation*.
4359 This will not be used if you return a response directly.
4361 Read more about it in the
4362 [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).
4363 """
4364 ),
4365 ] = Default(JSONResponse),
4366 name: Annotated[
4367 Optional[str],
4368 Doc(
4369 """
4370 Name for this *path operation*. Only used internally.
4371 """
4372 ),
4373 ] = None,
4374 callbacks: Annotated[
4375 Optional[List[BaseRoute]],
4376 Doc(
4377 """
4378 List of *path operations* that will be used as OpenAPI callbacks.
4380 This is only for OpenAPI documentation, the callbacks won't be used
4381 directly.
4383 It will be added to the generated OpenAPI (e.g. visible at `/docs`).
4385 Read more about it in the
4386 [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).
4387 """
4388 ),
4389 ] = None,
4390 openapi_extra: Annotated[
4391 Optional[Dict[str, Any]],
4392 Doc(
4393 """
4394 Extra metadata to be included in the OpenAPI schema for this *path
4395 operation*.
4397 Read more about it in the
4398 [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).
4399 """
4400 ),
4401 ] = None,
4402 generate_unique_id_function: Annotated[
4403 Callable[[routing.APIRoute], str],
4404 Doc(
4405 """
4406 Customize the function used to generate unique IDs for the *path
4407 operations* shown in the generated OpenAPI.
4409 This is particularly useful when automatically generating clients or
4410 SDKs for your API.
4412 Read more about it in the
4413 [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).
4414 """
4415 ),
4416 ] = Default(generate_unique_id),
4417 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4418 """
4419 Add a *path operation* using an HTTP TRACE operation.
4421 ## Example
4423 ```python
4424 from fastapi import FastAPI
4426 app = FastAPI()
4428 @app.put("/items/{item_id}")
4429 def trace_item(item_id: str):
4430 return None
4431 ```
4432 """
4433 return self.router.trace( 1abcde
4434 path,
4435 response_model=response_model,
4436 status_code=status_code,
4437 tags=tags,
4438 dependencies=dependencies,
4439 summary=summary,
4440 description=description,
4441 response_description=response_description,
4442 responses=responses,
4443 deprecated=deprecated,
4444 operation_id=operation_id,
4445 response_model_include=response_model_include,
4446 response_model_exclude=response_model_exclude,
4447 response_model_by_alias=response_model_by_alias,
4448 response_model_exclude_unset=response_model_exclude_unset,
4449 response_model_exclude_defaults=response_model_exclude_defaults,
4450 response_model_exclude_none=response_model_exclude_none,
4451 include_in_schema=include_in_schema,
4452 response_class=response_class,
4453 name=name,
4454 callbacks=callbacks,
4455 openapi_extra=openapi_extra,
4456 generate_unique_id_function=generate_unique_id_function,
4457 )
4459 def websocket_route( 1abcde
4460 self, path: str, name: Union[str, None] = None
4461 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4462 def decorator(func: DecoratedCallable) -> DecoratedCallable: 1abcde
4463 self.router.add_websocket_route(path, func, name=name) 1abcde
4464 return func 1abcde
4466 return decorator 1abcde
4468 @deprecated( 1abcde
4469 """
4470 on_event is deprecated, use lifespan event handlers instead.
4472 Read more about it in the
4473 [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).
4474 """
4475 )
4476 def on_event( 1abcde
4477 self,
4478 event_type: Annotated[
4479 str,
4480 Doc(
4481 """
4482 The type of event. `startup` or `shutdown`.
4483 """
4484 ),
4485 ],
4486 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4487 """
4488 Add an event handler for the application.
4490 `on_event` is deprecated, use `lifespan` event handlers instead.
4492 Read more about it in the
4493 [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
4494 """
4495 return self.router.on_event(event_type) 1abcde
4497 def middleware( 1abcde
4498 self,
4499 middleware_type: Annotated[
4500 str,
4501 Doc(
4502 """
4503 The type of middleware. Currently only supports `http`.
4504 """
4505 ),
4506 ],
4507 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4508 """
4509 Add a middleware to the application.
4511 Read more about it in the
4512 [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
4514 ## Example
4516 ```python
4517 import time
4519 from fastapi import FastAPI, Request
4521 app = FastAPI()
4524 @app.middleware("http")
4525 async def add_process_time_header(request: Request, call_next):
4526 start_time = time.time()
4527 response = await call_next(request)
4528 process_time = time.time() - start_time
4529 response.headers["X-Process-Time"] = str(process_time)
4530 return response
4531 ```
4532 """
4534 def decorator(func: DecoratedCallable) -> DecoratedCallable: 1abcde
4535 self.add_middleware(BaseHTTPMiddleware, dispatch=func) 1abcde
4536 return func 1abcde
4538 return decorator 1abcde
4540 def exception_handler( 1abcde
4541 self,
4542 exc_class_or_status_code: Annotated[
4543 Union[int, Type[Exception]],
4544 Doc(
4545 """
4546 The Exception class this would handle, or a status code.
4547 """
4548 ),
4549 ],
4550 ) -> Callable[[DecoratedCallable], DecoratedCallable]:
4551 """
4552 Add an exception handler to the app.
4554 Read more about it in the
4555 [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
4557 ## Example
4559 ```python
4560 from fastapi import FastAPI, Request
4561 from fastapi.responses import JSONResponse
4564 class UnicornException(Exception):
4565 def __init__(self, name: str):
4566 self.name = name
4569 app = FastAPI()
4572 @app.exception_handler(UnicornException)
4573 async def unicorn_exception_handler(request: Request, exc: UnicornException):
4574 return JSONResponse(
4575 status_code=418,
4576 content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
4577 )
4578 ```
4579 """
4581 def decorator(func: DecoratedCallable) -> DecoratedCallable: 1abcde
4582 self.add_exception_handler(exc_class_or_status_code, func) 1abcde
4583 return func 1abcde
4585 return decorator 1abcde