fastapi/applications.py PYTHON 4,692 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 4,692.
1from collections.abc import Awaitable, Callable, Coroutine, Sequence2from enum import Enum3from typing import Annotated, Any, TypeVar45from annotated_doc import Doc6from fastapi import routing7from fastapi.datastructures import Default, DefaultPlaceholder8from fastapi.exception_handlers import (9    http_exception_handler,10    request_validation_exception_handler,11    websocket_request_validation_exception_handler,12)13from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError14from fastapi.logger import logger15from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware16from fastapi.openapi.docs import (17    get_redoc_html,18    get_swagger_ui_html,19    get_swagger_ui_oauth2_redirect_html,20)21from fastapi.openapi.utils import get_openapi22from fastapi.params import Depends23from fastapi.types import DecoratedCallable, IncEx24from fastapi.utils import generate_unique_id25from starlette.applications import Starlette26from starlette.datastructures import State27from starlette.exceptions import HTTPException28from starlette.middleware import Middleware29from starlette.middleware.base import BaseHTTPMiddleware30from starlette.middleware.errors import ServerErrorMiddleware31from starlette.middleware.exceptions import ExceptionMiddleware32from starlette.requests import Request33from starlette.responses import HTMLResponse, JSONResponse, Response34from starlette.routing import BaseRoute35from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send36from typing_extensions import deprecated3738AppType = TypeVar("AppType", bound="FastAPI")394041class FastAPI(Starlette):42    """43    `FastAPI` app class, the main entrypoint to use FastAPI.4445    Read more in the46    [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).4748    ## Example4950    ```python51    from fastapi import FastAPI5253    app = FastAPI()54    ```55    """5657    def __init__(58        self: AppType,59        *,60        debug: Annotated[61            bool,62            Doc(63                """64                Boolean indicating if debug tracebacks should be returned on server65                errors.6667                Read more in the68                [Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application).69                """70            ),71        ] = False,72        routes: Annotated[73            list[BaseRoute] | None,74            Doc(75                """76                **Note**: you probably shouldn't use this parameter, it is inherited77                from Starlette and supported for compatibility.7879                ---8081                A list of routes to serve incoming HTTP and WebSocket requests.82                """83            ),84            deprecated(85                """86                You normally wouldn't use this parameter with FastAPI, it is inherited87                from Starlette and supported for compatibility.8889                In FastAPI, you normally would use the *path operation methods*,90                like `app.get()`, `app.post()`, etc.91                """92            ),93        ] = None,94        title: Annotated[95            str,96            Doc(97                """98                The title of the API.99100                It will be added to the generated OpenAPI (e.g. visible at `/docs`).101102                Read more in the103                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).104105                **Example**106107                ```python108                from fastapi import FastAPI109110                app = FastAPI(title="ChimichangApp")111                ```112                """113            ),114        ] = "FastAPI",115        summary: Annotated[116            str | None,117            Doc(118                """119                A short summary of the API.120121                It will be added to the generated OpenAPI (e.g. visible at `/docs`).122123                Read more in the124                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).125126                **Example**127128                ```python129                from fastapi import FastAPI130131                app = FastAPI(summary="Deadpond's favorite app. Nuff said.")132                ```133                """134            ),135        ] = None,136        description: Annotated[137            str,138            Doc(139                '''140                A description of the API. Supports Markdown (using141                [CommonMark syntax](https://commonmark.org/)).142143                It will be added to the generated OpenAPI (e.g. visible at `/docs`).144145                Read more in the146                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).147148                **Example**149150                ```python151                from fastapi import FastAPI152153                app = FastAPI(154                    description="""155                                ChimichangApp API helps you do awesome stuff. 🚀156157                                ## Items158159                                You can **read items**.160161                                ## Users162163                                You will be able to:164165                                * **Create users** (_not implemented_).166                                * **Read users** (_not implemented_).167168                                """169                )170                ```171                '''172            ),173        ] = "",174        version: Annotated[175            str,176            Doc(177                """178                The version of the API.179180                **Note** This is the version of your application, not the version of181                the OpenAPI specification nor the version of FastAPI being used.182183                It will be added to the generated OpenAPI (e.g. visible at `/docs`).184185                Read more in the186                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).187188                **Example**189190                ```python191                from fastapi import FastAPI192193                app = FastAPI(version="0.0.1")194                ```195                """196            ),197        ] = "0.1.0",198        openapi_url: Annotated[199            str | None,200            Doc(201                """202                The URL where the OpenAPI schema will be served from.203204                If you set it to `None`, no OpenAPI schema will be served publicly, and205                the default automatic endpoints `/docs` and `/redoc` will also be206                disabled.207208                Read more in the209                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).210211                **Example**212213                ```python214                from fastapi import FastAPI215216                app = FastAPI(openapi_url="/api/v1/openapi.json")217                ```218                """219            ),220        ] = "/openapi.json",221        openapi_tags: Annotated[222            list[dict[str, Any]] | None,223            Doc(224                """225                A list of tags used by OpenAPI, these are the same `tags` you can set226                in the *path operations*, like:227228                * `@app.get("/users/", tags=["users"])`229                * `@app.get("/items/", tags=["items"])`230231                The order of the tags can be used to specify the order shown in232                tools like Swagger UI, used in the automatic path `/docs`.233234                It's not required to specify all the tags used.235236                The tags that are not declared MAY be organized randomly or based237                on the tools' logic. Each tag name in the list MUST be unique.238239                The value of each item is a `dict` containing:240241                * `name`: The name of the tag.242                * `description`: A short description of the tag.243                    [CommonMark syntax](https://commonmark.org/) MAY be used for rich244                    text representation.245                * `externalDocs`: Additional external documentation for this tag. If246                    provided, it would contain a `dict` with:247                    * `description`: A short description of the target documentation.248                        [CommonMark syntax](https://commonmark.org/) MAY be used for249                        rich text representation.250                    * `url`: The URL for the target documentation. Value MUST be in251                        the form of a URL.252253                Read more in the254                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).255256                **Example**257258                ```python259                from fastapi import FastAPI260261                tags_metadata = [262                    {263                        "name": "users",264                        "description": "Operations with users. The **login** logic is also here.",265                    },266                    {267                        "name": "items",268                        "description": "Manage items. So _fancy_ they have their own docs.",269                        "externalDocs": {270                            "description": "Items external docs",271                            "url": "https://fastapi.tiangolo.com/",272                        },273                    },274                ]275276                app = FastAPI(openapi_tags=tags_metadata)277                ```278                """279            ),280        ] = None,281        servers: Annotated[282            list[dict[str, str | Any]] | None,283            Doc(284                """285                A `list` of `dict`s with connectivity information to a target server.286287                You would use it, for example, if your application is served from288                different domains and you want to use the same Swagger UI in the289                browser to interact with each of them (instead of having multiple290                browser tabs open). Or if you want to leave fixed the possible URLs.291292                If the servers `list` is not provided, or is an empty `list`, the293                `servers` property in the generated OpenAPI will be:294295                * a `dict` with a `url` value of the application's mounting point296                (`root_path`) if it's different from `/`.297                * otherwise, the `servers` property will be omitted from the OpenAPI298                schema.299300                Each item in the `list` is a `dict` containing:301302                * `url`: A URL to the target host. This URL supports Server Variables303                and MAY be relative, to indicate that the host location is relative304                to the location where the OpenAPI document is being served. Variable305                substitutions will be made when a variable is named in `{`brackets`}`.306                * `description`: An optional string describing the host designated by307                the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for308                rich text representation.309                * `variables`: A `dict` between a variable name and its value. The value310                    is used for substitution in the server's URL template.311312                Read more in the313                [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).314315                **Example**316317                ```python318                from fastapi import FastAPI319320                app = FastAPI(321                    servers=[322                        {"url": "https://stag.example.com", "description": "Staging environment"},323                        {"url": "https://prod.example.com", "description": "Production environment"},324                    ]325                )326                ```327                """328            ),329        ] = None,330        dependencies: Annotated[331            Sequence[Depends] | None,332            Doc(333                """334                A list of global dependencies, they will be applied to each335                *path operation*, including in sub-routers.336337                Read more about it in the338                [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).339340                **Example**341342                ```python343                from fastapi import Depends, FastAPI344345                from .dependencies import func_dep_1, func_dep_2346347                app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])348                ```349                """350            ),351        ] = None,352        default_response_class: Annotated[353            type[Response],354            Doc(355                """356                The default response class to be used.357358                Read more in the359                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).360361                **Example**362363                ```python364                from fastapi import FastAPI365                from fastapi.responses import ORJSONResponse366367                app = FastAPI(default_response_class=ORJSONResponse)368                ```369                """370            ),371        ] = Default(JSONResponse),372        redirect_slashes: Annotated[373            bool,374            Doc(375                """376                Whether to detect and redirect slashes in URLs when the client doesn't377                use the same format.378379                **Example**380381                ```python382                from fastapi import FastAPI383384                app = FastAPI(redirect_slashes=True)  # the default385386                @app.get("/items/")387                async def read_items():388                    return [{"item_id": "Foo"}]389                ```390391                With this app, if a client goes to `/items` (without a trailing slash),392                they will be automatically redirected with an HTTP status code of 307393                to `/items/`.394                """395            ),396        ] = True,397        docs_url: Annotated[398            str | None,399            Doc(400                """401                The path to the automatic interactive API documentation.402                It is handled in the browser by Swagger UI.403404                The default URL is `/docs`. You can disable it by setting it to `None`.405406                If `openapi_url` is set to `None`, this will be automatically disabled.407408                Read more in the409                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).410411                **Example**412413                ```python414                from fastapi import FastAPI415416                app = FastAPI(docs_url="/documentation", redoc_url=None)417                ```418                """419            ),420        ] = "/docs",421        redoc_url: Annotated[422            str | None,423            Doc(424                """425                The path to the alternative automatic interactive API documentation426                provided by ReDoc.427428                The default URL is `/redoc`. You can disable it by setting it to `None`.429430                If `openapi_url` is set to `None`, this will be automatically disabled.431432                Read more in the433                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).434435                **Example**436437                ```python438                from fastapi import FastAPI439440                app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")441                ```442                """443            ),444        ] = "/redoc",445        swagger_ui_oauth2_redirect_url: Annotated[446            str | None,447            Doc(448                """449                The OAuth2 redirect endpoint for the Swagger UI.450451                By default it is `/docs/oauth2-redirect`.452453                This is only used if you use OAuth2 (with the "Authorize" button)454                with Swagger UI.455                """456            ),457        ] = "/docs/oauth2-redirect",458        swagger_ui_init_oauth: Annotated[459            dict[str, Any] | None,460            Doc(461                """462                OAuth2 configuration for the Swagger UI, by default shown at `/docs`.463464                Read more about the available configuration options in the465                [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).466                """467            ),468        ] = None,469        middleware: Annotated[470            Sequence[Middleware] | None,471            Doc(472                """473                List of middleware to be added when creating the application.474475                In FastAPI you would normally do this with `app.add_middleware()`476                instead.477478                Read more in the479                [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).480                """481            ),482        ] = None,483        exception_handlers: Annotated[484            dict[485                int | type[Exception],486                Callable[[Request, Any], Coroutine[Any, Any, Response]],487            ]488            | None,489            Doc(490                """491                A dictionary with handlers for exceptions.492493                In FastAPI, you would normally use the decorator494                `@app.exception_handler()`.495496                Read more in the497                [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).498                """499            ),500        ] = None,501        on_startup: Annotated[502            Sequence[Callable[[], Any]] | None,503            Doc(504                """505                A list of startup event handler functions.506507                You should instead use the `lifespan` handlers.508509                Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).510                """511            ),512        ] = None,513        on_shutdown: Annotated[514            Sequence[Callable[[], Any]] | None,515            Doc(516                """517                A list of shutdown event handler functions.518519                You should instead use the `lifespan` handlers.520521                Read more in the522                [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).523                """524            ),525        ] = None,526        lifespan: Annotated[527            Lifespan[AppType] | None,528            Doc(529                """530                A `Lifespan` context manager handler. This replaces `startup` and531                `shutdown` functions with a single context manager.532533                Read more in the534                [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).535                """536            ),537        ] = None,538        terms_of_service: Annotated[539            str | None,540            Doc(541                """542                A URL to the Terms of Service for your API.543544                It will be added to the generated OpenAPI (e.g. visible at `/docs`).545546                Read more at the547                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).548549                **Example**550551                ```python552                app = FastAPI(terms_of_service="http://example.com/terms/")553                ```554                """555            ),556        ] = None,557        contact: Annotated[558            dict[str, str | Any] | None,559            Doc(560                """561                A dictionary with the contact information for the exposed API.562563                It can contain several fields.564565                * `name`: (`str`) The name of the contact person/organization.566                * `url`: (`str`) A URL pointing to the contact information. MUST be in567                    the format of a URL.568                * `email`: (`str`) The email address of the contact person/organization.569                    MUST be in the format of an email address.570571                It will be added to the generated OpenAPI (e.g. visible at `/docs`).572573                Read more at the574                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).575576                **Example**577578                ```python579                app = FastAPI(580                    contact={581                        "name": "Deadpoolio the Amazing",582                        "url": "http://x-force.example.com/contact/",583                        "email": "dp@x-force.example.com",584                    }585                )586                ```587                """588            ),589        ] = None,590        license_info: Annotated[591            dict[str, str | Any] | None,592            Doc(593                """594                A dictionary with the license information for the exposed API.595596                It can contain several fields.597598                * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The599                    license name used for the API.600                * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression601                    for the API. The `identifier` field is mutually exclusive of the `url`602                    field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.603                * `url`: (`str`) A URL to the license used for the API. This MUST be604                    the format of a URL.605606                It will be added to the generated OpenAPI (e.g. visible at `/docs`).607608                Read more at the609                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).610611                **Example**612613                ```python614                app = FastAPI(615                    license_info={616                        "name": "Apache 2.0",617                        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",618                    }619                )620                ```621                """622            ),623        ] = None,624        openapi_prefix: Annotated[625            str,626            Doc(627                """628                A URL prefix for the OpenAPI URL.629                """630            ),631            deprecated(632                """633                "openapi_prefix" has been deprecated in favor of "root_path", which634                follows more closely the ASGI standard, is simpler, and more635                automatic.636                """637            ),638        ] = "",639        root_path: Annotated[640            str,641            Doc(642                """643                A path prefix handled by a proxy that is not seen by the application644                but is seen by external clients, which affects things like Swagger UI.645646                Read more about it at the647                [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).648649                **Example**650651                ```python652                from fastapi import FastAPI653654                app = FastAPI(root_path="/api/v1")655                ```656                """657            ),658        ] = "",659        root_path_in_servers: Annotated[660            bool,661            Doc(662                """663                To disable automatically generating the URLs in the `servers` field664                in the autogenerated OpenAPI using the `root_path`.665666                Read more about it in the667                [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).668669                **Example**670671                ```python672                from fastapi import FastAPI673674                app = FastAPI(root_path_in_servers=False)675                ```676                """677            ),678        ] = True,679        responses: Annotated[680            dict[int | str, dict[str, Any]] | None,681            Doc(682                """683                Additional responses to be shown in OpenAPI.684685                It will be added to the generated OpenAPI (e.g. visible at `/docs`).686687                Read more about it in the688                [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).689690                And in the691                [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).692                """693            ),694        ] = None,695        callbacks: Annotated[696            list[BaseRoute] | None,697            Doc(698                """699                OpenAPI callbacks that should apply to all *path operations*.700701                It will be added to the generated OpenAPI (e.g. visible at `/docs`).702703                Read more about it in the704                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).705                """706            ),707        ] = None,708        webhooks: Annotated[709            routing.APIRouter | None,710            Doc(711                """712                Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't713                depend on specific *path operations*.714715                It will be added to the generated OpenAPI (e.g. visible at `/docs`).716717                **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.718719                Read more about it in the720                [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).721                """722            ),723        ] = None,724        deprecated: Annotated[725            bool | None,726            Doc(727                """728                Mark all *path operations* as deprecated. You probably don't need it,729                but it's available.730731                It will be added to the generated OpenAPI (e.g. visible at `/docs`).732733                Read more about it in the734                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).735                """736            ),737        ] = None,738        include_in_schema: Annotated[739            bool,740            Doc(741                """742                To include (or not) all the *path operations* in the generated OpenAPI.743                You probably don't need it, but it's available.744745                This affects the generated OpenAPI (e.g. visible at `/docs`).746747                Read more about it in the748                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).749                """750            ),751        ] = True,752        swagger_ui_parameters: Annotated[753            dict[str, Any] | None,754            Doc(755                """756                Parameters to configure Swagger UI, the autogenerated interactive API757                documentation (by default at `/docs`).758759                Read more about it in the760                [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).761                """762            ),763        ] = None,764        generate_unique_id_function: Annotated[765            Callable[[routing.APIRoute], str],766            Doc(767                """768                Customize the function used to generate unique IDs for the *path769                operations* shown in the generated OpenAPI.770771                This is particularly useful when automatically generating clients or772                SDKs for your API.773774                Read more about it in the775                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).776                """777            ),778        ] = Default(generate_unique_id),779        separate_input_output_schemas: Annotated[780            bool,781            Doc(782                """783                Whether to generate separate OpenAPI schemas for request body and784                response body when the results would be more precise.785786                This is particularly useful when automatically generating clients.787788                For example, if you have a model like:789790                ```python791                from pydantic import BaseModel792793                class Item(BaseModel):794                    name: str795                    tags: list[str] = []796                ```797798                When `Item` is used for input, a request body, `tags` is not required,799                the client doesn't have to provide it.800801                But when using `Item` for output, for a response body, `tags` is always802                available because it has a default value, even if it's just an empty803                list. So, the client should be able to always expect it.804805                In this case, there would be two different schemas, one for input and806                another one for output.807808                Read more about it in the809                [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)810                """811            ),812        ] = True,813        openapi_external_docs: Annotated[814            dict[str, Any] | None,815            Doc(816                """817                This field allows you to provide additional external documentation links.818                If provided, it must be a dictionary containing:819820                * `description`: A brief description of the external documentation.821                * `url`: The URL pointing to the external documentation. The value **MUST**822                be a valid URL format.823824                **Example**:825826                ```python827                from fastapi import FastAPI828829                external_docs = {830                    "description": "Detailed API Reference",831                    "url": "https://example.com/api-docs",832                }833834                app = FastAPI(openapi_external_docs=external_docs)835                ```836                """837            ),838        ] = None,839        strict_content_type: Annotated[840            bool,841            Doc(842                """843                Enable strict checking for request Content-Type headers.844845                When `True` (the default), requests with a body that do not include846                a `Content-Type` header will **not** be parsed as JSON.847848                This prevents potential cross-site request forgery (CSRF) attacks849                that exploit the browser's ability to send requests without a850                Content-Type header, bypassing CORS preflight checks. In particular851                applicable for apps that need to be run locally (in localhost).852853                When `False`, requests without a `Content-Type` header will have854                their body parsed as JSON, which maintains compatibility with855                certain clients that don't send `Content-Type` headers.856857                Read more about it in the858                [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).859                """860            ),861        ] = True,862        **extra: Annotated[863            Any,864            Doc(865                """866                Extra keyword arguments to be stored in the app, not used by FastAPI867                anywhere.868                """869            ),870        ],871    ) -> None:872        self.debug = debug873        self.title = title874        self.summary = summary875        self.description = description876        self.version = version877        self.terms_of_service = terms_of_service878        self.contact = contact879        self.license_info = license_info880        self.openapi_url = openapi_url881        self.openapi_tags = openapi_tags882        self.root_path_in_servers = root_path_in_servers883        self.docs_url = docs_url884        self.redoc_url = redoc_url885        self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url886        self.swagger_ui_init_oauth = swagger_ui_init_oauth887        self.swagger_ui_parameters = swagger_ui_parameters888        self.servers = servers or []889        self.separate_input_output_schemas = separate_input_output_schemas890        self.openapi_external_docs = openapi_external_docs891        self.extra = extra892        self.openapi_version: Annotated[893            str,894            Doc(895                """896                The version string of OpenAPI.897898                FastAPI will generate OpenAPI version 3.1.0, and will output that as899                the OpenAPI version. But some tools, even though they might be900                compatible with OpenAPI 3.1.0, might not recognize it as a valid.901902                So you could override this value to trick those tools into using903                the generated OpenAPI. Have in mind that this is a hack. But if you904                avoid using features added in OpenAPI 3.1.0, it might work for your905                use case.906907                This is not passed as a parameter to the `FastAPI` class to avoid908                giving the false idea that FastAPI would generate a different OpenAPI909                schema. It is only available as an attribute.910911                **Example**912913                ```python914                from fastapi import FastAPI915916                app = FastAPI()917918                app.openapi_version = "3.0.2"919                ```920                """921            ),922        ] = "3.1.0"923        self.openapi_schema: dict[str, Any] | None = None924        if self.openapi_url:925            assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"926            assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"927        # TODO: remove when discarding the openapi_prefix parameter928        if openapi_prefix:929            logger.warning(930                '"openapi_prefix" has been deprecated in favor of "root_path", which '931                "follows more closely the ASGI standard, is simpler, and more "932                "automatic. Check the docs at "933                "https://fastapi.tiangolo.com/advanced/sub-applications/"934            )935        self.webhooks: Annotated[936            routing.APIRouter,937            Doc(938                """939                The `app.webhooks` attribute is an `APIRouter` with the *path940                operations* that will be used just for documentation of webhooks.941942                Read more about it in the943                [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).944                """945            ),946        ] = webhooks or routing.APIRouter()947        self.root_path = root_path or openapi_prefix948        self.state: Annotated[949            State,950            Doc(951                """952                A state object for the application. This is the same object for the953                entire application, it doesn't change from request to request.954955                You normally wouldn't use this in FastAPI, for most of the cases you956                would instead use FastAPI dependencies.957958                This is simply inherited from Starlette.959960                Read more about it in the961                [Starlette docs for Applications](https://www.starlette.dev/applications/#storing-state-on-the-app-instance).962                """963            ),964        ] = State()965        self.dependency_overrides: Annotated[966            dict[Callable[..., Any], Callable[..., Any]],967            Doc(968                """969                A dictionary with overrides for the dependencies.970971                Each key is the original dependency callable, and the value is the972                actual dependency that should be called.973974                This is for testing, to replace expensive dependencies with testing975                versions.976977                Read more about it in the978                [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).979                """980            ),981        ] = {}982        self.router: routing.APIRouter = routing.APIRouter(983            routes=routes,984            redirect_slashes=redirect_slashes,985            dependency_overrides_provider=self,986            on_startup=on_startup,987            on_shutdown=on_shutdown,988            lifespan=lifespan,989            default_response_class=default_response_class,990            dependencies=dependencies,991            callbacks=callbacks,992            deprecated=deprecated,993            include_in_schema=include_in_schema,994            responses=responses,995            generate_unique_id_function=generate_unique_id_function,996            strict_content_type=strict_content_type,997        )998        self.exception_handlers: dict[999            Any, Callable[[Request, Any], Response | Awaitable[Response]]1000        ] = {} if exception_handlers is None else dict(exception_handlers)1001        self.exception_handlers.setdefault(HTTPException, http_exception_handler)1002        self.exception_handlers.setdefault(1003            RequestValidationError, request_validation_exception_handler1004        )10051006        # Starlette still has incorrect type specification for the handlers1007        self.exception_handlers.setdefault(1008            WebSocketRequestValidationError,1009            websocket_request_validation_exception_handler,  # type: ignore[arg-type]1010        )  # ty: ignore[no-matching-overload]10111012        self.user_middleware: list[Middleware] = (1013            [] if middleware is None else list(middleware)1014        )1015        self.middleware_stack: ASGIApp | None = None1016        self.setup()10171018    def build_middleware_stack(self) -> ASGIApp:1019        # Duplicate/override from Starlette to add AsyncExitStackMiddleware1020        # inside of ExceptionMiddleware, inside of custom user middlewares1021        debug = self.debug1022        error_handler = None1023        exception_handlers: dict[Any, ExceptionHandler] = {}10241025        for key, value in self.exception_handlers.items():1026            if key in (500, Exception):1027                error_handler = value1028            else:1029                exception_handlers[key] = value10301031        middleware = (1032            [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)]1033            + self.user_middleware1034            + [1035                Middleware(1036                    ExceptionMiddleware,1037                    handlers=exception_handlers,1038                    debug=debug,1039                ),1040                # Add FastAPI-specific AsyncExitStackMiddleware for closing files.1041                # Before this was also used for closing dependencies with yield but1042                # those now have their own AsyncExitStack, to properly support1043                # streaming responses while keeping compatibility with the previous1044                # versions (as of writing 0.117.1) that allowed doing1045                # except HTTPException inside a dependency with yield.1046                # This needs to happen after user middlewares because those create a1047                # new contextvars context copy by using a new AnyIO task group.1048                # This AsyncExitStack preserves the context for contextvars, not1049                # strictly necessary for closing files but it was one of the original1050                # intentions.1051                # If the AsyncExitStack lived outside of the custom middlewares and1052                # contextvars were set, for example in a dependency with 'yield'1053                # in that internal contextvars context, the values would not be1054                # available in the outer context of the AsyncExitStack.1055                # By placing the middleware and the AsyncExitStack here, inside all1056                # user middlewares, the same context is used.1057                # This is currently not needed, only for closing files, but used to be1058                # important when dependencies with yield were closed here.1059                Middleware(AsyncExitStackMiddleware),1060            ]1061        )10621063        app = self.router1064        for cls, args, kwargs in reversed(middleware):1065            app = cls(app, *args, **kwargs)1066        return app10671068    def openapi(self) -> dict[str, Any]:1069        """1070        Generate the OpenAPI schema of the application. This is called by FastAPI1071        internally.10721073        The first time it is called it stores the result in the attribute1074        `app.openapi_schema`, and next times it is called, it just returns that same1075        result. To avoid the cost of generating the schema every time.10761077        If you need to modify the generated OpenAPI schema, you could modify it.10781079        Read more in the1080        [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).1081        """1082        if not self.openapi_schema:1083            self.openapi_schema = get_openapi(1084                title=self.title,1085                version=self.version,1086                openapi_version=self.openapi_version,1087                summary=self.summary,1088                description=self.description,1089                terms_of_service=self.terms_of_service,1090                contact=self.contact,1091                license_info=self.license_info,1092                routes=self.routes,1093                webhooks=self.webhooks.routes,1094                tags=self.openapi_tags,1095                servers=self.servers,1096                separate_input_output_schemas=self.separate_input_output_schemas,1097                external_docs=self.openapi_external_docs,1098            )1099        return self.openapi_schema11001101    def setup(self) -> None:1102        if self.openapi_url:11031104            async def openapi(req: Request) -> JSONResponse:1105                root_path = req.scope.get("root_path", "").rstrip("/")1106                schema = self.openapi()1107                if root_path and self.root_path_in_servers:1108                    server_urls = {s.get("url") for s in schema.get("servers", [])}1109                    if root_path not in server_urls:1110                        schema = dict(schema)1111                        schema["servers"] = [{"url": root_path}] + schema.get(1112                            "servers", []1113                        )1114                return JSONResponse(schema)11151116            self.add_route(self.openapi_url, openapi, include_in_schema=False)1117        if self.openapi_url and self.docs_url:11181119            async def swagger_ui_html(req: Request) -> HTMLResponse:1120                root_path = req.scope.get("root_path", "").rstrip("/")1121                openapi_url = root_path + self.openapi_url1122                oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url1123                if oauth2_redirect_url:1124                    oauth2_redirect_url = root_path + oauth2_redirect_url1125                return get_swagger_ui_html(1126                    openapi_url=openapi_url,1127                    title=f"{self.title} - Swagger UI",1128                    oauth2_redirect_url=oauth2_redirect_url,1129                    init_oauth=self.swagger_ui_init_oauth,1130                    swagger_ui_parameters=self.swagger_ui_parameters,1131                )11321133            self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)11341135            if self.swagger_ui_oauth2_redirect_url:11361137                async def swagger_ui_redirect(req: Request) -> HTMLResponse:1138                    return get_swagger_ui_oauth2_redirect_html()11391140                self.add_route(1141                    self.swagger_ui_oauth2_redirect_url,1142                    swagger_ui_redirect,1143                    include_in_schema=False,1144                )1145        if self.openapi_url and self.redoc_url:11461147            async def redoc_html(req: Request) -> HTMLResponse:1148                root_path = req.scope.get("root_path", "").rstrip("/")1149                openapi_url = root_path + self.openapi_url1150                return get_redoc_html(1151                    openapi_url=openapi_url, title=f"{self.title} - ReDoc"1152                )11531154            self.add_route(self.redoc_url, redoc_html, include_in_schema=False)11551156    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:1157        if self.root_path:1158            scope["root_path"] = self.root_path1159        await super().__call__(scope, receive, send)11601161    def add_api_route(1162        self,1163        path: str,1164        endpoint: Callable[..., Any],1165        *,1166        response_model: Any = Default(None),1167        status_code: int | None = None,1168        tags: list[str | Enum] | None = None,1169        dependencies: Sequence[Depends] | None = None,1170        summary: str | None = None,1171        description: str | None = None,1172        response_description: str = "Successful Response",1173        responses: dict[int | str, dict[str, Any]] | None = None,1174        deprecated: bool | None = None,1175        methods: list[str] | None = None,1176        operation_id: str | None = None,1177        response_model_include: IncEx | None = None,1178        response_model_exclude: IncEx | None = None,1179        response_model_by_alias: bool = True,1180        response_model_exclude_unset: bool = False,1181        response_model_exclude_defaults: bool = False,1182        response_model_exclude_none: bool = False,1183        include_in_schema: bool = True,1184        response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),1185        name: str | None = None,1186        openapi_extra: dict[str, Any] | None = None,1187        generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(1188            generate_unique_id1189        ),1190    ) -> None:1191        self.router.add_api_route(1192            path,1193            endpoint=endpoint,1194            response_model=response_model,1195            status_code=status_code,1196            tags=tags,1197            dependencies=dependencies,1198            summary=summary,1199            description=description,1200            response_description=response_description,1201            responses=responses,1202            deprecated=deprecated,1203            methods=methods,1204            operation_id=operation_id,1205            response_model_include=response_model_include,1206            response_model_exclude=response_model_exclude,1207            response_model_by_alias=response_model_by_alias,1208            response_model_exclude_unset=response_model_exclude_unset,1209            response_model_exclude_defaults=response_model_exclude_defaults,1210            response_model_exclude_none=response_model_exclude_none,1211            include_in_schema=include_in_schema,1212            response_class=response_class,1213            name=name,1214            openapi_extra=openapi_extra,1215            generate_unique_id_function=generate_unique_id_function,1216        )12171218    def api_route(1219        self,1220        path: str,1221        *,1222        response_model: Any = Default(None),1223        status_code: int | None = None,1224        tags: list[str | Enum] | None = None,1225        dependencies: Sequence[Depends] | None = None,1226        summary: str | None = None,1227        description: str | None = None,1228        response_description: str = "Successful Response",1229        responses: dict[int | str, dict[str, Any]] | None = None,1230        deprecated: bool | None = None,1231        methods: list[str] | None = None,1232        operation_id: str | None = None,1233        response_model_include: IncEx | None = None,1234        response_model_exclude: IncEx | None = None,1235        response_model_by_alias: bool = True,1236        response_model_exclude_unset: bool = False,1237        response_model_exclude_defaults: bool = False,1238        response_model_exclude_none: bool = False,1239        include_in_schema: bool = True,1240        response_class: type[Response] = Default(JSONResponse),1241        name: str | None = None,1242        openapi_extra: dict[str, Any] | None = None,1243        generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(1244            generate_unique_id1245        ),1246    ) -> Callable[[DecoratedCallable], DecoratedCallable]:1247        def decorator(func: DecoratedCallable) -> DecoratedCallable:1248            self.router.add_api_route(1249                path,1250                func,1251                response_model=response_model,1252                status_code=status_code,1253                tags=tags,1254                dependencies=dependencies,1255                summary=summary,1256                description=description,1257                response_description=response_description,1258                responses=responses,1259                deprecated=deprecated,1260                methods=methods,1261                operation_id=operation_id,1262                response_model_include=response_model_include,1263                response_model_exclude=response_model_exclude,1264                response_model_by_alias=response_model_by_alias,1265                response_model_exclude_unset=response_model_exclude_unset,1266                response_model_exclude_defaults=response_model_exclude_defaults,1267                response_model_exclude_none=response_model_exclude_none,1268                include_in_schema=include_in_schema,1269                response_class=response_class,1270                name=name,1271                openapi_extra=openapi_extra,1272                generate_unique_id_function=generate_unique_id_function,1273            )1274            return func12751276        return decorator12771278    def add_api_websocket_route(1279        self,1280        path: str,1281        endpoint: Callable[..., Any],1282        name: str | None = None,1283        *,1284        dependencies: Sequence[Depends] | None = None,1285    ) -> None:1286        self.router.add_api_websocket_route(1287            path,1288            endpoint,1289            name=name,1290            dependencies=dependencies,1291        )12921293    def websocket(1294        self,1295        path: Annotated[1296            str,1297            Doc(1298                """1299                WebSocket path.1300                """1301            ),1302        ],1303        name: Annotated[1304            str | None,1305            Doc(1306                """1307                A name for the WebSocket. Only used internally.1308                """1309            ),1310        ] = None,1311        *,1312        dependencies: Annotated[1313            Sequence[Depends] | None,1314            Doc(1315                """1316                A list of dependencies (using `Depends()`) to be used for this1317                WebSocket.13181319                Read more about it in the1320                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).1321                """1322            ),1323        ] = None,1324    ) -> Callable[[DecoratedCallable], DecoratedCallable]:1325        """1326        Decorate a WebSocket function.13271328        Read more about it in the1329        [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).13301331        **Example**13321333        ```python1334        from fastapi import FastAPI, WebSocket13351336        app = FastAPI()13371338        @app.websocket("/ws")1339        async def websocket_endpoint(websocket: WebSocket):1340            await websocket.accept()1341            while True:1342                data = await websocket.receive_text()1343                await websocket.send_text(f"Message text was: {data}")1344        ```1345        """13461347        def decorator(func: DecoratedCallable) -> DecoratedCallable:1348            self.add_api_websocket_route(1349                path,1350                func,1351                name=name,1352                dependencies=dependencies,1353            )1354            return func13551356        return decorator13571358    def include_router(1359        self,1360        router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],1361        *,1362        prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",1363        tags: Annotated[1364            list[str | Enum] | None,1365            Doc(1366                """1367                A list of tags to be applied to all the *path operations* in this1368                router.13691370                It will be added to the generated OpenAPI (e.g. visible at `/docs`).13711372                Read more about it in the1373                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).1374                """1375            ),1376        ] = None,1377        dependencies: Annotated[1378            Sequence[Depends] | None,1379            Doc(1380                """1381                A list of dependencies (using `Depends()`) to be applied to all the1382                *path operations* in this router.13831384                Read more about it in the1385                [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).13861387                **Example**13881389                ```python1390                from fastapi import Depends, FastAPI13911392                from .dependencies import get_token_header1393                from .internal import admin13941395                app = FastAPI()13961397                app.include_router(1398                    admin.router,1399                    dependencies=[Depends(get_token_header)],1400                )1401                ```1402                """1403            ),1404        ] = None,1405        responses: Annotated[1406            dict[int | str, dict[str, Any]] | None,1407            Doc(1408                """1409                Additional responses to be shown in OpenAPI.14101411                It will be added to the generated OpenAPI (e.g. visible at `/docs`).14121413                Read more about it in the1414                [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).14151416                And in the1417                [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).1418                """1419            ),1420        ] = None,1421        deprecated: Annotated[1422            bool | None,1423            Doc(1424                """1425                Mark all the *path operations* in this router as deprecated.14261427                It will be added to the generated OpenAPI (e.g. visible at `/docs`).14281429                **Example**14301431                ```python1432                from fastapi import FastAPI14331434                from .internal import old_api14351436                app = FastAPI()14371438                app.include_router(1439                    old_api.router,1440                    deprecated=True,1441                )1442                ```1443                """1444            ),1445        ] = None,1446        include_in_schema: Annotated[1447            bool,1448            Doc(1449                """1450                Include (or not) all the *path operations* in this router in the1451                generated OpenAPI schema.14521453                This affects the generated OpenAPI (e.g. visible at `/docs`).14541455                **Example**14561457                ```python1458                from fastapi import FastAPI14591460                from .internal import old_api14611462                app = FastAPI()14631464                app.include_router(1465                    old_api.router,1466                    include_in_schema=False,1467                )1468                ```1469                """1470            ),1471        ] = True,1472        default_response_class: Annotated[1473            type[Response],1474            Doc(1475                """1476                Default response class to be used for the *path operations* in this1477                router.14781479                Read more in the1480                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).14811482                **Example**14831484                ```python1485                from fastapi import FastAPI1486                from fastapi.responses import ORJSONResponse14871488                from .internal import old_api14891490                app = FastAPI()14911492                app.include_router(1493                    old_api.router,1494                    default_response_class=ORJSONResponse,1495                )1496                ```1497                """1498            ),1499        ] = Default(JSONResponse),1500        callbacks: Annotated[1501            list[BaseRoute] | None,1502            Doc(1503                """1504                List of *path operations* that will be used as OpenAPI callbacks.15051506                This is only for OpenAPI documentation, the callbacks won't be used1507                directly.15081509                It will be added to the generated OpenAPI (e.g. visible at `/docs`).15101511                Read more about it in the1512                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).1513                """1514            ),1515        ] = None,1516        generate_unique_id_function: Annotated[1517            Callable[[routing.APIRoute], str],1518            Doc(1519                """1520                Customize the function used to generate unique IDs for the *path1521                operations* shown in the generated OpenAPI.15221523                This is particularly useful when automatically generating clients or1524                SDKs for your API.15251526                Read more about it in the1527                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).1528                """1529            ),1530        ] = Default(generate_unique_id),1531    ) -> None:1532        """1533        Include an `APIRouter` in the same app.15341535        Read more about it in the1536        [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).15371538        ## Example15391540        ```python1541        from fastapi import FastAPI15421543        from .users import users_router15441545        app = FastAPI()15461547        app.include_router(users_router)1548        ```1549        """1550        self.router.include_router(1551            router,1552            prefix=prefix,1553            tags=tags,1554            dependencies=dependencies,1555            responses=responses,1556            deprecated=deprecated,1557            include_in_schema=include_in_schema,1558            default_response_class=default_response_class,1559            callbacks=callbacks,1560            generate_unique_id_function=generate_unique_id_function,1561        )15621563    def get(1564        self,1565        path: Annotated[1566            str,1567            Doc(1568                """1569                The URL path to be used for this *path operation*.15701571                For example, in `http://example.com/items`, the path is `/items`.1572                """1573            ),1574        ],1575        *,1576        response_model: Annotated[1577            Any,1578            Doc(1579                """1580                The type to use for the response.15811582                It could be any valid Pydantic *field* type. So, it doesn't have to1583                be a Pydantic model, it could be other things, like a `list`, `dict`,1584                etc.15851586                It will be used for:15871588                * Documentation: the generated OpenAPI (and the UI at `/docs`) will1589                    show it as the response (JSON Schema).1590                * Serialization: you could return an arbitrary object and the1591                    `response_model` would be used to serialize that object into the1592                    corresponding JSON.1593                * Filtering: the JSON sent to the client will only contain the data1594                    (fields) defined in the `response_model`. If you returned an object1595                    that contains an attribute `password` but the `response_model` does1596                    not include that field, the JSON sent to the client would not have1597                    that `password`.1598                * Validation: whatever you return will be serialized with the1599                    `response_model`, converting any data as necessary to generate the1600                    corresponding JSON. But if the data in the object returned is not1601                    valid, that would mean a violation of the contract with the client,1602                    so it's an error from the API developer. So, FastAPI will raise an1603                    error and return a 500 error code (Internal Server Error).16041605                Read more about it in the1606                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).1607                """1608            ),1609        ] = Default(None),1610        status_code: Annotated[1611            int | None,1612            Doc(1613                """1614                The default status code to be used for the response.16151616                You could override the status code by returning a response directly.16171618                Read more about it in the1619                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).1620                """1621            ),1622        ] = None,1623        tags: Annotated[1624            list[str | Enum] | None,1625            Doc(1626                """1627                A list of tags to be applied to the *path operation*.16281629                It will be added to the generated OpenAPI (e.g. visible at `/docs`).16301631                Read more about it in the1632                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).1633                """1634            ),1635        ] = None,1636        dependencies: Annotated[1637            Sequence[Depends] | None,1638            Doc(1639                """1640                A list of dependencies (using `Depends()`) to be applied to the1641                *path operation*.16421643                Read more about it in the1644                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).1645                """1646            ),1647        ] = None,1648        summary: Annotated[1649            str | None,1650            Doc(1651                """1652                A summary for the *path operation*.16531654                It will be added to the generated OpenAPI (e.g. visible at `/docs`).16551656                Read more about it in the1657                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).1658                """1659            ),1660        ] = None,1661        description: Annotated[1662            str | None,1663            Doc(1664                """1665                A description for the *path operation*.16661667                If not provided, it will be extracted automatically from the docstring1668                of the *path operation function*.16691670                It can contain Markdown.16711672                It will be added to the generated OpenAPI (e.g. visible at `/docs`).16731674                Read more about it in the1675                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).1676                """1677            ),1678        ] = None,1679        response_description: Annotated[1680            str,1681            Doc(1682                """1683                The description for the default response.16841685                It will be added to the generated OpenAPI (e.g. visible at `/docs`).1686                """1687            ),1688        ] = "Successful Response",1689        responses: Annotated[1690            dict[int | str, dict[str, Any]] | None,1691            Doc(1692                """1693                Additional responses that could be returned by this *path operation*.16941695                It will be added to the generated OpenAPI (e.g. visible at `/docs`).1696                """1697            ),1698        ] = None,1699        deprecated: Annotated[1700            bool | None,1701            Doc(1702                """1703                Mark this *path operation* as deprecated.17041705                It will be added to the generated OpenAPI (e.g. visible at `/docs`).1706                """1707            ),1708        ] = None,1709        operation_id: Annotated[1710            str | None,1711            Doc(1712                """1713                Custom operation ID to be used by this *path operation*.17141715                By default, it is generated automatically.17161717                If you provide a custom operation ID, you need to make sure it is1718                unique for the whole API.17191720                You can customize the1721                operation ID generation with the parameter1722                `generate_unique_id_function` in the `FastAPI` class.17231724                Read more about it in the1725                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).1726                """1727            ),1728        ] = None,1729        response_model_include: Annotated[1730            IncEx | None,1731            Doc(1732                """1733                Configuration passed to Pydantic to include only certain fields in the1734                response data.17351736                Read more about it in the1737                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).1738                """1739            ),1740        ] = None,1741        response_model_exclude: Annotated[1742            IncEx | None,1743            Doc(1744                """1745                Configuration passed to Pydantic to exclude certain fields in the1746                response data.17471748                Read more about it in the1749                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).1750                """1751            ),1752        ] = None,1753        response_model_by_alias: Annotated[1754            bool,1755            Doc(1756                """1757                Configuration passed to Pydantic to define if the response model1758                should be serialized by alias when an alias is used.17591760                Read more about it in the1761                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).1762                """1763            ),1764        ] = True,1765        response_model_exclude_unset: Annotated[1766            bool,1767            Doc(1768                """1769                Configuration passed to Pydantic to define if the response data1770                should have all the fields, including the ones that were not set and1771                have their default values. This is different from1772                `response_model_exclude_defaults` in that if the fields are set,1773                they will be included in the response, even if the value is the same1774                as the default.17751776                When `True`, default values are omitted from the response.17771778                Read more about it in the1779                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).1780                """1781            ),1782        ] = False,1783        response_model_exclude_defaults: Annotated[1784            bool,1785            Doc(1786                """1787                Configuration passed to Pydantic to define if the response data1788                should have all the fields, including the ones that have the same value1789                as the default. This is different from `response_model_exclude_unset`1790                in that if the fields are set but contain the same default values,1791                they will be excluded from the response.17921793                When `True`, default values are omitted from the response.17941795                Read more about it in the1796                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).1797                """1798            ),1799        ] = False,1800        response_model_exclude_none: Annotated[1801            bool,1802            Doc(1803                """1804                Configuration passed to Pydantic to define if the response data should1805                exclude fields set to `None`.18061807                This is much simpler (less smart) than `response_model_exclude_unset`1808                and `response_model_exclude_defaults`. You probably want to use one of1809                those two instead of this one, as those allow returning `None` values1810                when it makes sense.18111812                Read more about it in the1813                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).1814                """1815            ),1816        ] = False,1817        include_in_schema: Annotated[1818            bool,1819            Doc(1820                """1821                Include this *path operation* in the generated OpenAPI schema.18221823                This affects the generated OpenAPI (e.g. visible at `/docs`).18241825                Read more about it in the1826                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).1827                """1828            ),1829        ] = True,1830        response_class: Annotated[1831            type[Response],1832            Doc(1833                """1834                Response class to be used for this *path operation*.18351836                This will not be used if you return a response directly.18371838                Read more about it in the1839                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).1840                """1841            ),1842        ] = Default(JSONResponse),1843        name: Annotated[1844            str | None,1845            Doc(1846                """1847                Name for this *path operation*. Only used internally.1848                """1849            ),1850        ] = None,1851        callbacks: Annotated[1852            list[BaseRoute] | None,1853            Doc(1854                """1855                List of *path operations* that will be used as OpenAPI callbacks.18561857                This is only for OpenAPI documentation, the callbacks won't be used1858                directly.18591860                It will be added to the generated OpenAPI (e.g. visible at `/docs`).18611862                Read more about it in the1863                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).1864                """1865            ),1866        ] = None,1867        openapi_extra: Annotated[1868            dict[str, Any] | None,1869            Doc(1870                """1871                Extra metadata to be included in the OpenAPI schema for this *path1872                operation*.18731874                Read more about it in the1875                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).1876                """1877            ),1878        ] = None,1879        generate_unique_id_function: Annotated[1880            Callable[[routing.APIRoute], str],1881            Doc(1882                """1883                Customize the function used to generate unique IDs for the *path1884                operations* shown in the generated OpenAPI.18851886                This is particularly useful when automatically generating clients or1887                SDKs for your API.18881889                Read more about it in the1890                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).1891                """1892            ),1893        ] = Default(generate_unique_id),1894    ) -> Callable[[DecoratedCallable], DecoratedCallable]:1895        """1896        Add a *path operation* using an HTTP GET operation.18971898        ## Example18991900        ```python1901        from fastapi import FastAPI19021903        app = FastAPI()19041905        @app.get("/items/")1906        def read_items():1907            return [{"name": "Empanada"}, {"name": "Arepa"}]1908        ```1909        """1910        return self.router.get(1911            path,1912            response_model=response_model,1913            status_code=status_code,1914            tags=tags,1915            dependencies=dependencies,1916            summary=summary,1917            description=description,1918            response_description=response_description,1919            responses=responses,1920            deprecated=deprecated,1921            operation_id=operation_id,1922            response_model_include=response_model_include,1923            response_model_exclude=response_model_exclude,1924            response_model_by_alias=response_model_by_alias,1925            response_model_exclude_unset=response_model_exclude_unset,1926            response_model_exclude_defaults=response_model_exclude_defaults,1927            response_model_exclude_none=response_model_exclude_none,1928            include_in_schema=include_in_schema,1929            response_class=response_class,1930            name=name,1931            callbacks=callbacks,1932            openapi_extra=openapi_extra,1933            generate_unique_id_function=generate_unique_id_function,1934        )19351936    def put(1937        self,1938        path: Annotated[1939            str,1940            Doc(1941                """1942                The URL path to be used for this *path operation*.19431944                For example, in `http://example.com/items`, the path is `/items`.1945                """1946            ),1947        ],1948        *,1949        response_model: Annotated[1950            Any,1951            Doc(1952                """1953                The type to use for the response.19541955                It could be any valid Pydantic *field* type. So, it doesn't have to1956                be a Pydantic model, it could be other things, like a `list`, `dict`,1957                etc.19581959                It will be used for:19601961                * Documentation: the generated OpenAPI (and the UI at `/docs`) will1962                    show it as the response (JSON Schema).1963                * Serialization: you could return an arbitrary object and the1964                    `response_model` would be used to serialize that object into the1965                    corresponding JSON.1966                * Filtering: the JSON sent to the client will only contain the data1967                    (fields) defined in the `response_model`. If you returned an object1968                    that contains an attribute `password` but the `response_model` does1969                    not include that field, the JSON sent to the client would not have1970                    that `password`.1971                * Validation: whatever you return will be serialized with the1972                    `response_model`, converting any data as necessary to generate the1973                    corresponding JSON. But if the data in the object returned is not1974                    valid, that would mean a violation of the contract with the client,1975                    so it's an error from the API developer. So, FastAPI will raise an1976                    error and return a 500 error code (Internal Server Error).19771978                Read more about it in the1979                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).1980                """1981            ),1982        ] = Default(None),1983        status_code: Annotated[1984            int | None,1985            Doc(1986                """1987                The default status code to be used for the response.19881989                You could override the status code by returning a response directly.19901991                Read more about it in the1992                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).1993                """1994            ),1995        ] = None,1996        tags: Annotated[1997            list[str | Enum] | None,1998            Doc(1999                """2000                A list of tags to be applied to the *path operation*.

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.