fastapi/applications.py PYTHON 4,839 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 4,839.
1import os2from collections.abc import Awaitable, Callable, Coroutine, Sequence3from enum import Enum4from typing import Annotated, Any, Literal, TypeVar56from annotated_doc import Doc7from fastapi import routing8from fastapi.datastructures import Default, DefaultPlaceholder9from fastapi.exception_handlers import (10    http_exception_handler,11    request_validation_exception_handler,12    websocket_request_validation_exception_handler,13)14from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError15from fastapi.logger import logger16from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware17from fastapi.openapi.docs import (18    get_redoc_html,19    get_swagger_ui_html,20    get_swagger_ui_oauth2_redirect_html,21)22from fastapi.openapi.utils import get_openapi23from fastapi.params import Depends24from fastapi.telemetry import TelemetryConfig25from fastapi.telemetry._asgi import (26    ExceptionTelemetryMiddleware,27    NativeTelemetry,28    _legacy_otel,29)30from fastapi.types import DecoratedCallable, IncEx31from fastapi.utils import generate_unique_id32from starlette.applications import Starlette33from starlette.datastructures import State34from starlette.exceptions import HTTPException35from starlette.middleware import Middleware36from starlette.middleware.base import BaseHTTPMiddleware37from starlette.middleware.errors import ServerErrorMiddleware38from starlette.middleware.exceptions import ExceptionMiddleware39from starlette.requests import Request40from starlette.responses import HTMLResponse, JSONResponse, Response41from starlette.routing import BaseRoute42from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send43from typing_extensions import deprecated4445AppType = TypeVar("AppType", bound="FastAPI")464748class FastAPI(Starlette):49    """50    `FastAPI` app class, the main entrypoint to use FastAPI.5152    Read more in the53    [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).5455    ## Example5657    ```python58    from fastapi import FastAPI5960    app = FastAPI()61    ```62    """6364    def __init__(65        self: AppType,66        *,67        telemetry: Annotated[68            TelemetryConfig | None,69            Doc(70                """71                Native OpenTelemetry configuration as a dictionary. Uses global72                providers by default. Omitted options keep their defaults.7374                ```python75                app = FastAPI(telemetry={"tracing": False})76                ```77                """78            ),79        ] = None,80        debug: Annotated[81            bool,82            Doc(83                """84                Boolean indicating if debug tracebacks should be returned on server85                errors.8687                Read more in the88                [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette).89                """90            ),91        ] = False,92        routes: Annotated[93            list[BaseRoute] | None,94            Doc(95                """96                **Note**: you probably shouldn't use this parameter, it is inherited97                from Starlette and supported for compatibility.9899                ---100101                A list of routes to serve incoming HTTP and WebSocket requests.102                """103            ),104            deprecated(105                """106                You normally wouldn't use this parameter with FastAPI, it is inherited107                from Starlette and supported for compatibility.108109                In FastAPI, you normally would use the *path operation methods*,110                like `app.get()`, `app.post()`, etc.111                """112            ),113        ] = None,114        title: Annotated[115            str,116            Doc(117                """118                The title of the API.119120                It will be added to the generated OpenAPI (e.g. visible at `/docs`).121122                Read more in the123                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).124125                **Example**126127                ```python128                from fastapi import FastAPI129130                app = FastAPI(title="ChimichangApp")131                ```132                """133            ),134        ] = "FastAPI",135        summary: Annotated[136            str | None,137            Doc(138                """139                A short summary of the API.140141                It will be added to the generated OpenAPI (e.g. visible at `/docs`).142143                Read more in the144                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).145146                **Example**147148                ```python149                from fastapi import FastAPI150151                app = FastAPI(summary="Deadpond's favorite app. Nuff said.")152                ```153                """154            ),155        ] = None,156        description: Annotated[157            str,158            Doc(159                '''160                A description of the API. Supports Markdown (using161                [CommonMark syntax](https://commonmark.org/)).162163                It will be added to the generated OpenAPI (e.g. visible at `/docs`).164165                Read more in the166                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).167168                **Example**169170                ```python171                from fastapi import FastAPI172173                app = FastAPI(174                    description="""175                                ChimichangApp API helps you do awesome stuff. 🚀176177                                ## Items178179                                You can **read items**.180181                                ## Users182183                                You will be able to:184185                                * **Create users** (_not implemented_).186                                * **Read users** (_not implemented_).187188                                """189                )190                ```191                '''192            ),193        ] = "",194        version: Annotated[195            str,196            Doc(197                """198                The version of the API.199200                **Note** This is the version of your application, not the version of201                the OpenAPI specification nor the version of FastAPI being used.202203                It will be added to the generated OpenAPI (e.g. visible at `/docs`).204205                Read more in the206                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).207208                **Example**209210                ```python211                from fastapi import FastAPI212213                app = FastAPI(version="0.0.1")214                ```215                """216            ),217        ] = "0.1.0",218        openapi_url: Annotated[219            str | None,220            Doc(221                """222                The URL where the OpenAPI schema will be served from.223224                If you set it to `None`, no OpenAPI schema will be served publicly, and225                the default automatic endpoints `/docs` and `/redoc` will also be226                disabled.227228                Read more in the229                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).230231                **Example**232233                ```python234                from fastapi import FastAPI235236                app = FastAPI(openapi_url="/api/v1/openapi.json")237                ```238                """239            ),240        ] = "/openapi.json",241        openapi_tags: Annotated[242            list[dict[str, Any]] | None,243            Doc(244                """245                A list of tags used by OpenAPI, these are the same `tags` you can set246                in the *path operations*, like:247248                * `@app.get("/users/", tags=["users"])`249                * `@app.get("/items/", tags=["items"])`250251                The order of the tags can be used to specify the order shown in252                tools like Swagger UI, used in the automatic path `/docs`.253254                It's not required to specify all the tags used.255256                The tags that are not declared MAY be organized randomly or based257                on the tools' logic. Each tag name in the list MUST be unique.258259                The value of each item is a `dict` containing:260261                * `name`: The name of the tag.262                * `description`: A short description of the tag.263                    [CommonMark syntax](https://commonmark.org/) MAY be used for rich264                    text representation.265                * `externalDocs`: Additional external documentation for this tag. If266                    provided, it would contain a `dict` with:267                    * `description`: A short description of the target documentation.268                        [CommonMark syntax](https://commonmark.org/) MAY be used for269                        rich text representation.270                    * `url`: The URL for the target documentation. Value MUST be in271                        the form of a URL.272273                Read more in the274                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).275276                **Example**277278                ```python279                from fastapi import FastAPI280281                tags_metadata = [282                    {283                        "name": "users",284                        "description": "Operations with users. The **login** logic is also here.",285                    },286                    {287                        "name": "items",288                        "description": "Manage items. So _fancy_ they have their own docs.",289                        "externalDocs": {290                            "description": "Items external docs",291                            "url": "https://fastapi.tiangolo.com/",292                        },293                    },294                ]295296                app = FastAPI(openapi_tags=tags_metadata)297                ```298                """299            ),300        ] = None,301        servers: Annotated[302            list[dict[str, str | Any]] | None,303            Doc(304                """305                A `list` of `dict`s with connectivity information to a target server.306307                You would use it, for example, if your application is served from308                different domains and you want to use the same Swagger UI in the309                browser to interact with each of them (instead of having multiple310                browser tabs open). Or if you want to leave fixed the possible URLs.311312                If the servers `list` is not provided, or is an empty `list`, the313                `servers` property in the generated OpenAPI will be:314315                * a `dict` with a `url` value of the application's mounting point316                (`root_path`) if it's different from `/`.317                * otherwise, the `servers` property will be omitted from the OpenAPI318                schema.319320                Each item in the `list` is a `dict` containing:321322                * `url`: A URL to the target host. This URL supports Server Variables323                and MAY be relative, to indicate that the host location is relative324                to the location where the OpenAPI document is being served. Variable325                substitutions will be made when a variable is named in `{`brackets`}`.326                * `description`: An optional string describing the host designated by327                the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for328                rich text representation.329                * `variables`: A `dict` between a variable name and its value. The value330                    is used for substitution in the server's URL template.331332                Read more in the333                [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).334335                **Example**336337                ```python338                from fastapi import FastAPI339340                app = FastAPI(341                    servers=[342                        {"url": "https://stag.example.com", "description": "Staging environment"},343                        {"url": "https://prod.example.com", "description": "Production environment"},344                    ]345                )346                ```347                """348            ),349        ] = None,350        dependencies: Annotated[351            Sequence[Depends] | None,352            Doc(353                """354                A list of global dependencies, they will be applied to each355                *path operation*, including in sub-routers.356357                Read more about it in the358                [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).359360                **Example**361362                ```python363                from fastapi import Depends, FastAPI364365                from .dependencies import func_dep_1, func_dep_2366367                app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])368                ```369                """370            ),371        ] = None,372        default_response_class: Annotated[373            type[Response],374            Doc(375                """376                The default response class to be used.377378                Read more in the379                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).380381                **Example**382383                ```python384                from fastapi import FastAPI385                from fastapi.responses import ORJSONResponse386387                app = FastAPI(default_response_class=ORJSONResponse)388                ```389                """390            ),391        ] = Default(JSONResponse),392        redirect_slashes: Annotated[393            bool,394            Doc(395                """396                Whether to detect and redirect slashes in URLs when the client doesn't397                use the same format.398399                **Example**400401                ```python402                from fastapi import FastAPI403404                app = FastAPI(redirect_slashes=True)  # the default405406                @app.get("/items/")407                async def read_items():408                    return [{"item_id": "Foo"}]409                ```410411                With this app, if a client goes to `/items` (without a trailing slash),412                they will be automatically redirected with an HTTP status code of 307413                to `/items/`.414                """415            ),416        ] = True,417        docs_url: Annotated[418            str | None,419            Doc(420                """421                The path to the automatic interactive API documentation.422                It is handled in the browser by Swagger UI.423424                The default URL is `/docs`. You can disable it by setting it to `None`.425426                If `openapi_url` is set to `None`, this will be automatically disabled.427428                Read more in the429                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).430431                **Example**432433                ```python434                from fastapi import FastAPI435436                app = FastAPI(docs_url="/documentation", redoc_url=None)437                ```438                """439            ),440        ] = "/docs",441        redoc_url: Annotated[442            str | None,443            Doc(444                """445                The path to the alternative automatic interactive API documentation446                provided by ReDoc.447448                The default URL is `/redoc`. You can disable it by setting it to `None`.449450                If `openapi_url` is set to `None`, this will be automatically disabled.451452                Read more in the453                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).454455                **Example**456457                ```python458                from fastapi import FastAPI459460                app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")461                ```462                """463            ),464        ] = "/redoc",465        swagger_ui_oauth2_redirect_url: Annotated[466            str | None,467            Doc(468                """469                The OAuth2 redirect endpoint for the Swagger UI.470471                By default it is `/docs/oauth2-redirect`.472473                This is only used if you use OAuth2 (with the "Authorize" button)474                with Swagger UI.475                """476            ),477        ] = "/docs/oauth2-redirect",478        swagger_ui_init_oauth: Annotated[479            dict[str, Any] | None,480            Doc(481                """482                OAuth2 configuration for the Swagger UI, by default shown at `/docs`.483484                Read more about the available configuration options in the485                [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).486                """487            ),488        ] = None,489        middleware: Annotated[490            Sequence[Middleware] | None,491            Doc(492                """493                List of middleware to be added when creating the application.494495                In FastAPI you would normally do this with `app.add_middleware()`496                instead.497498                Read more in the499                [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).500                """501            ),502        ] = None,503        exception_handlers: Annotated[504            dict[505                int | type[Exception],506                Callable[[Request, Any], Coroutine[Any, Any, Response]],507            ]508            | None,509            Doc(510                """511                A dictionary with handlers for exceptions.512513                In FastAPI, you would normally use the decorator514                `@app.exception_handler()`.515516                Read more in the517                [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).518                """519            ),520        ] = None,521        on_startup: Annotated[522            Sequence[Callable[[], Any]] | None,523            Doc(524                """525                A list of startup event handler functions.526527                You should instead use the `lifespan` handlers.528529                Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).530                """531            ),532        ] = None,533        on_shutdown: Annotated[534            Sequence[Callable[[], Any]] | None,535            Doc(536                """537                A list of shutdown event handler functions.538539                You should instead use the `lifespan` handlers.540541                Read more in the542                [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).543                """544            ),545        ] = None,546        lifespan: Annotated[547            Lifespan[AppType] | None,548            Doc(549                """550                A `Lifespan` context manager handler. This replaces `startup` and551                `shutdown` functions with a single context manager.552553                Read more in the554                [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).555                """556            ),557        ] = None,558        terms_of_service: Annotated[559            str | None,560            Doc(561                """562                A URL to the Terms of Service for your API.563564                It will be added to the generated OpenAPI (e.g. visible at `/docs`).565566                Read more at the567                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).568569                **Example**570571                ```python572                app = FastAPI(terms_of_service="http://example.com/terms/")573                ```574                """575            ),576        ] = None,577        contact: Annotated[578            dict[str, str | Any] | None,579            Doc(580                """581                A dictionary with the contact information for the exposed API.582583                It can contain several fields.584585                * `name`: (`str`) The name of the contact person/organization.586                * `url`: (`str`) A URL pointing to the contact information. MUST be in587                    the format of a URL.588                * `email`: (`str`) The email address of the contact person/organization.589                    MUST be in the format of an email address.590591                It will be added to the generated OpenAPI (e.g. visible at `/docs`).592593                Read more at the594                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).595596                **Example**597598                ```python599                app = FastAPI(600                    contact={601                        "name": "Deadpoolio the Amazing",602                        "url": "http://x-force.example.com/contact/",603                        "email": "dp@x-force.example.com",604                    }605                )606                ```607                """608            ),609        ] = None,610        license_info: Annotated[611            dict[str, str | Any] | None,612            Doc(613                """614                A dictionary with the license information for the exposed API.615616                It can contain several fields.617618                * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The619                    license name used for the API.620                * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression621                    for the API. The `identifier` field is mutually exclusive of the `url`622                    field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.623                * `url`: (`str`) A URL to the license used for the API. This MUST be624                    the format of a URL.625626                It will be added to the generated OpenAPI (e.g. visible at `/docs`).627628                Read more at the629                [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).630631                **Example**632633                ```python634                app = FastAPI(635                    license_info={636                        "name": "Apache 2.0",637                        "url": "https://www.apache.org/licenses/LICENSE-2.0.html",638                    }639                )640                ```641                """642            ),643        ] = None,644        openapi_prefix: Annotated[645            str,646            Doc(647                """648                A URL prefix for the OpenAPI URL.649                """650            ),651            deprecated(652                """653                "openapi_prefix" has been deprecated in favor of "root_path", which654                follows more closely the ASGI standard, is simpler, and more655                automatic.656                """657            ),658        ] = "",659        root_path: Annotated[660            str,661            Doc(662                """663                A path prefix handled by a proxy that is not seen by the application664                but is seen by external clients, which affects things like Swagger UI.665666                Read more about it at the667                [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).668669                **Example**670671                ```python672                from fastapi import FastAPI673674                app = FastAPI(root_path="/api/v1")675                ```676                """677            ),678        ] = "",679        root_path_in_servers: Annotated[680            bool,681            Doc(682                """683                To disable automatically generating the URLs in the `servers` field684                in the autogenerated OpenAPI using the `root_path`.685686                Read more about it in the687                [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).688689                **Example**690691                ```python692                from fastapi import FastAPI693694                app = FastAPI(root_path_in_servers=False)695                ```696                """697            ),698        ] = True,699        responses: Annotated[700            dict[int | str, dict[str, Any]] | None,701            Doc(702                """703                Additional responses to be shown in OpenAPI.704705                It will be added to the generated OpenAPI (e.g. visible at `/docs`).706707                Read more about it in the708                [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).709710                And in the711                [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).712                """713            ),714        ] = None,715        callbacks: Annotated[716            list[BaseRoute] | None,717            Doc(718                """719                OpenAPI callbacks that should apply to all *path operations*.720721                It will be added to the generated OpenAPI (e.g. visible at `/docs`).722723                Read more about it in the724                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).725                """726            ),727        ] = None,728        webhooks: Annotated[729            routing.APIRouter | None,730            Doc(731                """732                Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't733                depend on specific *path operations*.734735                It will be added to the generated OpenAPI (e.g. visible at `/docs`).736737                **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.738739                Read more about it in the740                [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).741                """742            ),743        ] = None,744        deprecated: Annotated[745            bool | None,746            Doc(747                """748                Mark all *path operations* as deprecated. You probably don't need it,749                but it's available.750751                It will be added to the generated OpenAPI (e.g. visible at `/docs`).752753                Read more about it in the754                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).755                """756            ),757        ] = None,758        include_in_schema: Annotated[759            bool,760            Doc(761                """762                To include (or not) all the *path operations* in the generated OpenAPI.763                You probably don't need it, but it's available.764765                This affects the generated OpenAPI (e.g. visible at `/docs`).766767                Read more about it in the768                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).769                """770            ),771        ] = True,772        swagger_ui_parameters: Annotated[773            dict[str, Any] | None,774            Doc(775                """776                Parameters to configure Swagger UI, the autogenerated interactive API777                documentation (by default at `/docs`).778779                Read more about it in the780                [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).781                """782            ),783        ] = None,784        generate_unique_id_function: Annotated[785            Callable[[routing.APIRoute], str],786            Doc(787                """788                Customize the function used to generate unique IDs for the *path789                operations* shown in the generated OpenAPI.790791                This is particularly useful when automatically generating clients or792                SDKs for your API.793794                Read more about it in the795                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).796                """797            ),798        ] = Default(generate_unique_id),799        separate_input_output_schemas: Annotated[800            bool,801            Doc(802                """803                Whether to generate separate OpenAPI schemas for request body and804                response body when the results would be more precise.805806                This is particularly useful when automatically generating clients.807808                For example, if you have a model like:809810                ```python811                from pydantic import BaseModel812813                class Item(BaseModel):814                    name: str815                    tags: list[str] = []816                ```817818                When `Item` is used for input, a request body, `tags` is not required,819                the client doesn't have to provide it.820821                But when using `Item` for output, for a response body, `tags` is always822                available because it has a default value, even if it's just an empty823                list. So, the client should be able to always expect it.824825                In this case, there would be two different schemas, one for input and826                another one for output.827828                Read more about it in the829                [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)830                """831            ),832        ] = True,833        openapi_external_docs: Annotated[834            dict[str, Any] | None,835            Doc(836                """837                This field allows you to provide additional external documentation links.838                If provided, it must be a dictionary containing:839840                * `description`: A brief description of the external documentation.841                * `url`: The URL pointing to the external documentation. The value **MUST**842                be a valid URL format.843844                **Example**:845846                ```python847                from fastapi import FastAPI848849                external_docs = {850                    "description": "Detailed API Reference",851                    "url": "https://example.com/api-docs",852                }853854                app = FastAPI(openapi_external_docs=external_docs)855                ```856                """857            ),858        ] = None,859        strict_content_type: Annotated[860            bool,861            Doc(862                """863                Enable strict checking for request Content-Type headers.864865                When `True` (the default), requests with a body that do not include866                a `Content-Type` header will **not** be parsed as JSON.867868                This prevents potential cross-site request forgery (CSRF) attacks869                that exploit the browser's ability to send requests without a870                Content-Type header, bypassing CORS preflight checks. In particular871                applicable for apps that need to be run locally (in localhost).872873                When `False`, requests without a `Content-Type` header will have874                their body parsed as JSON, which maintains compatibility with875                certain clients that don't send `Content-Type` headers.876877                Read more about it in the878                [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).879                """880            ),881        ] = True,882        **extra: Annotated[883            Any,884            Doc(885                """886                Extra keyword arguments to be stored in the app, not used by FastAPI887                anywhere.888                """889            ),890        ],891    ) -> None:892        self.debug = debug893        self.title = title894        self.summary = summary895        self.description = description896        self.version = version897        self.terms_of_service = terms_of_service898        self.contact = contact899        self.license_info = license_info900        self.openapi_url = openapi_url901        self.openapi_tags = openapi_tags902        self.root_path_in_servers = root_path_in_servers903        self.docs_url = docs_url904        self.redoc_url = redoc_url905        self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url906        self.swagger_ui_init_oauth = swagger_ui_init_oauth907        self.swagger_ui_parameters = swagger_ui_parameters908        self.servers = servers or []909        self.separate_input_output_schemas = separate_input_output_schemas910        self.openapi_external_docs = openapi_external_docs911        self.extra = extra912        self.openapi_version: Annotated[913            str,914            Doc(915                """916                The version string of OpenAPI.917918                FastAPI will generate OpenAPI version 3.1.0, and will output that as919                the OpenAPI version. But some tools, even though they might be920                compatible with OpenAPI 3.1.0, might not recognize it as a valid.921922                So you could override this value to trick those tools into using923                the generated OpenAPI. Have in mind that this is a hack. But if you924                avoid using features added in OpenAPI 3.1.0, it might work for your925                use case.926927                This is not passed as a parameter to the `FastAPI` class to avoid928                giving the false idea that FastAPI would generate a different OpenAPI929                schema. It is only available as an attribute.930931                **Example**932933                ```python934                from fastapi import FastAPI935936                app = FastAPI()937938                app.openapi_version = "3.0.2"939                ```940                """941            ),942        ] = "3.1.0"943        self.openapi_schema: dict[str, Any] | None = None944        self._openapi_routes_version: int | None = None945        if self.openapi_url:946            assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"947            assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"948        # TODO: remove when discarding the openapi_prefix parameter949        if openapi_prefix:950            logger.warning(951                '"openapi_prefix" has been deprecated in favor of "root_path", which '952                "follows more closely the ASGI standard, is simpler, and more "953                "automatic. Check the docs at "954                "https://fastapi.tiangolo.com/advanced/sub-applications/"955            )956        self.webhooks: Annotated[957            routing.APIRouter,958            Doc(959                """960                The `app.webhooks` attribute is an `APIRouter` with the *path961                operations* that will be used just for documentation of webhooks.962963                Read more about it in the964                [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).965                """966            ),967        ] = webhooks or routing.APIRouter()968        self.root_path = root_path or openapi_prefix969        self.state: Annotated[970            State,971            Doc(972                """973                A state object for the application. This is the same object for the974                entire application, it doesn't change from request to request.975976                You normally wouldn't use this in FastAPI, for most of the cases you977                would instead use FastAPI dependencies.978979                This is simply inherited from Starlette.980981                Read more about it in the982                [Starlette docs for Applications](https://starlette.dev/applications/#storing-state-on-the-app-instance).983                """984            ),985        ] = State()986        self.dependency_overrides: Annotated[987            dict[Callable[..., Any], Callable[..., Any]],988            Doc(989                """990                A dictionary with overrides for the dependencies.991992                Each key is the original dependency callable, and the value is the993                actual dependency that should be called.994995                This is for testing, to replace expensive dependencies with testing996                versions.997998                Read more about it in the999                [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/).1000                """1001            ),1002        ] = {}1003        self.router: routing.APIRouter = routing.APIRouter(1004            routes=routes,1005            redirect_slashes=redirect_slashes,1006            dependency_overrides_provider=self,1007            on_startup=on_startup,1008            on_shutdown=on_shutdown,1009            lifespan=lifespan,1010            default_response_class=default_response_class,1011            dependencies=dependencies,1012            callbacks=callbacks,1013            deprecated=deprecated,1014            include_in_schema=include_in_schema,1015            responses=responses,1016            generate_unique_id_function=generate_unique_id_function,1017            strict_content_type=strict_content_type,1018        )1019        self.exception_handlers: dict[1020            Any, Callable[[Request, Any], Response | Awaitable[Response]]1021        ] = {} if exception_handlers is None else dict(exception_handlers)1022        self.exception_handlers.setdefault(HTTPException, http_exception_handler)1023        self.exception_handlers.setdefault(1024            RequestValidationError, request_validation_exception_handler1025        )10261027        # Starlette still has incorrect type specification for the handlers1028        self.exception_handlers.setdefault(1029            WebSocketRequestValidationError,1030            websocket_request_validation_exception_handler,  # type: ignore[arg-type]1031        )  # ty: ignore[no-matching-overload]10321033        self._telemetry: TelemetryConfig = {1034            "tracer_provider": None,1035            "meter_provider": None,1036            "logger_provider": None,1037            "tracing": True,1038            "metrics": True,1039            "logs": True,1040            "operation_spans": True,1041            "auto_configure": os.getenv("FASTAPI_OTEL_AUTO_CONFIGURE", "").lower()1042            == "true",1043            "exclude": None,1044            **(telemetry if telemetry is not None else {}),1045        }1046        self._native_telemetry = NativeTelemetry(self._telemetry)10471048        self.user_middleware: list[Middleware] = (1049            [] if middleware is None else list(middleware)1050        )1051        self.middleware_stack: ASGIApp | None = None1052        self.setup()10531054    def build_middleware_stack(self) -> ASGIApp:1055        # Duplicate/override from Starlette to add AsyncExitStackMiddleware1056        # inside of ExceptionMiddleware, inside of custom user middlewares1057        debug = self.debug1058        error_handler = None1059        exception_handlers: dict[Any, ExceptionHandler] = {}10601061        for key, value in self.exception_handlers.items():1062            if key in (500, Exception):1063                error_handler = value1064            else:1065                exception_handlers[key] = value10661067        middleware = (1068            [1069                Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug),1070                Middleware(ExceptionTelemetryMiddleware),1071            ]1072            + self.user_middleware1073            + [1074                Middleware(1075                    ExceptionMiddleware,1076                    handlers=exception_handlers,1077                    debug=debug,1078                ),1079                # Add FastAPI-specific AsyncExitStackMiddleware for closing files.1080                # Before this was also used for closing dependencies with yield but1081                # those now have their own AsyncExitStack, to properly support1082                # streaming responses while keeping compatibility with the previous1083                # versions (as of writing 0.117.1) that allowed doing1084                # except HTTPException inside a dependency with yield.1085                # This needs to happen after user middlewares because those create a1086                # new contextvars context copy by using a new AnyIO task group.1087                # This AsyncExitStack preserves the context for contextvars, not1088                # strictly necessary for closing files but it was one of the original1089                # intentions.1090                # If the AsyncExitStack lived outside of the custom middlewares and1091                # contextvars were set, for example in a dependency with 'yield'1092                # in that internal contextvars context, the values would not be1093                # available in the outer context of the AsyncExitStack.1094                # By placing the middleware and the AsyncExitStack here, inside all1095                # user middlewares, the same context is used.1096                # This is currently not needed, only for closing files, but used to be1097                # important when dependencies with yield were closed here.1098                Middleware(AsyncExitStackMiddleware),1099            ]1100        )11011102        app = self.router1103        for cls, args, kwargs in reversed(middleware):1104            app = cls(app, *args, **kwargs)1105        return app11061107    def openapi(self) -> dict[str, Any]:1108        """1109        Generate the OpenAPI schema of the application. This is called by FastAPI1110        internally.11111112        The first time it is called it stores the result in the attribute1113        `app.openapi_schema`, and next times it is called, it just returns that same1114        result. To avoid the cost of generating the schema every time.11151116        If you need to modify the generated OpenAPI schema, you could modify it.11171118        Read more in the1119        [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).1120        """1121        routes_version = self.router._get_routes_version()1122        if not self.openapi_schema or self._openapi_routes_version != routes_version:1123            self.openapi_schema = get_openapi(1124                title=self.title,1125                version=self.version,1126                openapi_version=self.openapi_version,1127                summary=self.summary,1128                description=self.description,1129                terms_of_service=self.terms_of_service,1130                contact=self.contact,1131                license_info=self.license_info,1132                routes=self.routes,1133                webhooks=self.webhooks.routes,1134                tags=self.openapi_tags,1135                servers=self.servers,1136                separate_input_output_schemas=self.separate_input_output_schemas,1137                external_docs=self.openapi_external_docs,1138            )1139            self._openapi_routes_version = routes_version1140        return self.openapi_schema11411142    def setup(self) -> None:1143        if self.openapi_url:11441145            async def openapi(req: Request) -> JSONResponse:1146                root_path = req.scope.get("root_path", "").rstrip("/")1147                schema = self.openapi()1148                if root_path and self.root_path_in_servers:1149                    server_urls = {s.get("url") for s in schema.get("servers", [])}1150                    if root_path not in server_urls:1151                        schema = dict(schema)1152                        schema["servers"] = [{"url": root_path}] + schema.get(1153                            "servers", []1154                        )1155                return JSONResponse(schema)11561157            self.add_route(self.openapi_url, openapi, include_in_schema=False)1158        if self.openapi_url and self.docs_url:11591160            async def swagger_ui_html(req: Request) -> HTMLResponse:1161                root_path = req.scope.get("root_path", "").rstrip("/")1162                openapi_url = root_path + self.openapi_url1163                oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url1164                if oauth2_redirect_url:1165                    oauth2_redirect_url = root_path + oauth2_redirect_url1166                return get_swagger_ui_html(1167                    openapi_url=openapi_url,1168                    title=f"{self.title} - Swagger UI",1169                    oauth2_redirect_url=oauth2_redirect_url,1170                    init_oauth=self.swagger_ui_init_oauth,1171                    swagger_ui_parameters=self.swagger_ui_parameters,1172                )11731174            self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False)11751176            if self.swagger_ui_oauth2_redirect_url:11771178                async def swagger_ui_redirect(req: Request) -> HTMLResponse:1179                    return get_swagger_ui_oauth2_redirect_html()11801181                self.add_route(1182                    self.swagger_ui_oauth2_redirect_url,1183                    swagger_ui_redirect,1184                    include_in_schema=False,1185                )1186        if self.openapi_url and self.redoc_url:11871188            async def redoc_html(req: Request) -> HTMLResponse:1189                root_path = req.scope.get("root_path", "").rstrip("/")1190                openapi_url = root_path + self.openapi_url1191                return get_redoc_html(1192                    openapi_url=openapi_url, title=f"{self.title} - ReDoc"1193                )11941195            self.add_route(self.redoc_url, redoc_html, include_in_schema=False)11961197    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:1198        if self.root_path:1199            scope["root_path"] = self.root_path1200        if scope["type"] == "lifespan":1201            from fastapi.telemetry._runtime import lifespan12021203            await lifespan(1204                config=self._telemetry,1205                app=super().__call__,1206                scope=scope,1207                receive=receive,1208                send=send,1209            )1210            return1211        if (1212            scope["type"] not in ("http", "websocket")1213            or "fastapi.telemetry" in scope1214            or not self._native_telemetry.enabled()1215        ):1216            await super().__call__(scope, receive, send)1217            return1218        if self.middleware_stack is None:1219            self.middleware_stack = self.build_middleware_stack()1220        scope["app"] = self1221        await self._native_telemetry(1222            app=super().__call__,1223            scope=scope,1224            receive=receive,1225            send=send,1226            legacy_otel=_legacy_otel(self.middleware_stack),1227        )12281229    def add_api_route(1230        self,1231        path: str,1232        endpoint: Callable[..., Any],1233        *,1234        response_model: Any = Default(None),1235        status_code: int | None = None,1236        tags: list[str | Enum] | None = None,1237        dependencies: Sequence[Depends] | None = None,1238        summary: str | None = None,1239        description: str | None = None,1240        response_description: str = "Successful Response",1241        responses: dict[int | str, dict[str, Any]] | None = None,1242        deprecated: bool | None = None,1243        methods: list[str] | None = None,1244        operation_id: str | None = None,1245        response_model_include: IncEx | None = None,1246        response_model_exclude: IncEx | None = None,1247        response_model_by_alias: bool = True,1248        response_model_exclude_unset: bool = False,1249        response_model_exclude_defaults: bool = False,1250        response_model_exclude_none: bool = False,1251        include_in_schema: bool = True,1252        response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),1253        name: str | None = None,1254        openapi_extra: dict[str, Any] | None = None,1255        generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(1256            generate_unique_id1257        ),1258    ) -> None:1259        self.router.add_api_route(1260            path,1261            endpoint=endpoint,1262            response_model=response_model,1263            status_code=status_code,1264            tags=tags,1265            dependencies=dependencies,1266            summary=summary,1267            description=description,1268            response_description=response_description,1269            responses=responses,1270            deprecated=deprecated,1271            methods=methods,1272            operation_id=operation_id,1273            response_model_include=response_model_include,1274            response_model_exclude=response_model_exclude,1275            response_model_by_alias=response_model_by_alias,1276            response_model_exclude_unset=response_model_exclude_unset,1277            response_model_exclude_defaults=response_model_exclude_defaults,1278            response_model_exclude_none=response_model_exclude_none,1279            include_in_schema=include_in_schema,1280            response_class=response_class,1281            name=name,1282            openapi_extra=openapi_extra,1283            generate_unique_id_function=generate_unique_id_function,1284        )12851286    def frontend(1287        self,1288        path: Annotated[1289            str,1290            Doc(1291                """1292                The URL path prefix where the frontend build should be served.1293                """1294            ),1295        ],1296        *,1297        directory: Annotated[1298            str | os.PathLike[str],1299            Doc(1300                """1301                The directory containing the static frontend build output.1302                """1303            ),1304        ],1305        fallback: Annotated[1306            Literal["auto", "index.html", "404.html"] | None,1307            Doc(1308                """1309                The fallback file behavior for missing frontend paths.1310                """1311            ),1312        ] = "auto",1313        check_dir: Annotated[1314            bool | Literal["auto"],1315            Doc(1316                """1317                Check that the frontend directory exists when the app is created. When1318                set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is1319                `"development"`, and check it otherwise. The `fastapi dev` command1320                sets `FASTAPI_ENV` to `"development"` if it is not already set.1321                """1322            ),1323        ] = "auto",1324    ) -> None:1325        """1326        Serve a static frontend build as low-priority routes.13271328        Use this for frontend tools that build static files into a directory,1329        such as `dist`. **FastAPI** path operations are checked first, and1330        the frontend files are checked only if no normal route matched.13311332        A typical project could look like this:13331334        ```text1335        .1336        ├── pyproject.toml1337        ├── app1338        │   ├── __init__.py1339        │   └── main.py1340        └── dist1341            ├── index.html1342            └── assets1343                └── app.js1344        ```13451346        Then in `app/main.py`:13471348        ```python1349        from fastapi import FastAPI13501351        app = FastAPI()1352        app.frontend("/", directory="dist")1353        ```1354        """1355        check_dir = routing._resolve_frontend_check_dir(1356            directory=directory, check_dir=check_dir1357        )1358        self.router.frontend(1359            path,1360            directory=directory,1361            fallback=fallback,1362            check_dir=check_dir,1363        )13641365    def api_route(1366        self,1367        path: str,1368        *,1369        response_model: Any = Default(None),1370        status_code: int | None = None,1371        tags: list[str | Enum] | None = None,1372        dependencies: Sequence[Depends] | None = None,1373        summary: str | None = None,1374        description: str | None = None,1375        response_description: str = "Successful Response",1376        responses: dict[int | str, dict[str, Any]] | None = None,1377        deprecated: bool | None = None,1378        methods: list[str] | None = None,1379        operation_id: str | None = None,1380        response_model_include: IncEx | None = None,1381        response_model_exclude: IncEx | None = None,1382        response_model_by_alias: bool = True,1383        response_model_exclude_unset: bool = False,1384        response_model_exclude_defaults: bool = False,1385        response_model_exclude_none: bool = False,1386        include_in_schema: bool = True,1387        response_class: type[Response] = Default(JSONResponse),1388        name: str | None = None,1389        openapi_extra: dict[str, Any] | None = None,1390        generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(1391            generate_unique_id1392        ),1393    ) -> Callable[[DecoratedCallable], DecoratedCallable]:1394        def decorator(func: DecoratedCallable) -> DecoratedCallable:1395            self.router.add_api_route(1396                path,1397                func,1398                response_model=response_model,1399                status_code=status_code,1400                tags=tags,1401                dependencies=dependencies,1402                summary=summary,1403                description=description,1404                response_description=response_description,1405                responses=responses,1406                deprecated=deprecated,1407                methods=methods,1408                operation_id=operation_id,1409                response_model_include=response_model_include,1410                response_model_exclude=response_model_exclude,1411                response_model_by_alias=response_model_by_alias,1412                response_model_exclude_unset=response_model_exclude_unset,1413                response_model_exclude_defaults=response_model_exclude_defaults,1414                response_model_exclude_none=response_model_exclude_none,1415                include_in_schema=include_in_schema,1416                response_class=response_class,1417                name=name,1418                openapi_extra=openapi_extra,1419                generate_unique_id_function=generate_unique_id_function,1420            )1421            return func14221423        return decorator14241425    def add_api_websocket_route(1426        self,1427        path: str,1428        endpoint: Callable[..., Any],1429        name: str | None = None,1430        *,1431        dependencies: Sequence[Depends] | None = None,1432    ) -> None:1433        self.router.add_api_websocket_route(1434            path,1435            endpoint,1436            name=name,1437            dependencies=dependencies,1438        )14391440    def websocket(1441        self,1442        path: Annotated[1443            str,1444            Doc(1445                """1446                WebSocket path.1447                """1448            ),1449        ],1450        name: Annotated[1451            str | None,1452            Doc(1453                """1454                A name for the WebSocket. Only used internally.1455                """1456            ),1457        ] = None,1458        *,1459        dependencies: Annotated[1460            Sequence[Depends] | None,1461            Doc(1462                """1463                A list of dependencies (using `Depends()`) to be used for this1464                WebSocket.14651466                Read more about it in the1467                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).1468                """1469            ),1470        ] = None,1471    ) -> Callable[[DecoratedCallable], DecoratedCallable]:1472        """1473        Decorate a WebSocket function.14741475        Read more about it in the1476        [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).14771478        **Example**14791480        ```python1481        from fastapi import FastAPI, WebSocket14821483        app = FastAPI()14841485        @app.websocket("/ws")1486        async def websocket_endpoint(websocket: WebSocket):1487            await websocket.accept()1488            while True:1489                data = await websocket.receive_text()1490                await websocket.send_text(f"Message text was: {data}")1491        ```1492        """14931494        def decorator(func: DecoratedCallable) -> DecoratedCallable:1495            self.add_api_websocket_route(1496                path,1497                func,1498                name=name,1499                dependencies=dependencies,1500            )1501            return func15021503        return decorator15041505    def include_router(1506        self,1507        router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")],1508        *,1509        prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",1510        tags: Annotated[1511            list[str | Enum] | None,1512            Doc(1513                """1514                A list of tags to be applied to all the *path operations* in this1515                router.15161517                It will be added to the generated OpenAPI (e.g. visible at `/docs`).15181519                Read more about it in the1520                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).1521                """1522            ),1523        ] = None,1524        dependencies: Annotated[1525            Sequence[Depends] | None,1526            Doc(1527                """1528                A list of dependencies (using `Depends()`) to be applied to all the1529                *path operations* in this router.15301531                Read more about it in the1532                [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).15331534                **Example**15351536                ```python1537                from fastapi import Depends, FastAPI15381539                from .dependencies import get_token_header1540                from .internal import admin15411542                app = FastAPI()15431544                app.include_router(1545                    admin.router,1546                    dependencies=[Depends(get_token_header)],1547                )1548                ```1549                """1550            ),1551        ] = None,1552        responses: Annotated[1553            dict[int | str, dict[str, Any]] | None,1554            Doc(1555                """1556                Additional responses to be shown in OpenAPI.15571558                It will be added to the generated OpenAPI (e.g. visible at `/docs`).15591560                Read more about it in the1561                [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).15621563                And in the1564                [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).1565                """1566            ),1567        ] = None,1568        deprecated: Annotated[1569            bool | None,1570            Doc(1571                """1572                Mark all the *path operations* in this router as deprecated.15731574                It will be added to the generated OpenAPI (e.g. visible at `/docs`).15751576                **Example**15771578                ```python1579                from fastapi import FastAPI15801581                from .internal import old_api15821583                app = FastAPI()15841585                app.include_router(1586                    old_api.router,1587                    deprecated=True,1588                )1589                ```1590                """1591            ),1592        ] = None,1593        include_in_schema: Annotated[1594            bool,1595            Doc(1596                """1597                Include (or not) all the *path operations* in this router in the1598                generated OpenAPI schema.15991600                This affects the generated OpenAPI (e.g. visible at `/docs`).16011602                **Example**16031604                ```python1605                from fastapi import FastAPI16061607                from .internal import old_api16081609                app = FastAPI()16101611                app.include_router(1612                    old_api.router,1613                    include_in_schema=False,1614                )1615                ```1616                """1617            ),1618        ] = True,1619        default_response_class: Annotated[1620            type[Response],1621            Doc(1622                """1623                Default response class to be used for the *path operations* in this1624                router.16251626                Read more in the1627                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).16281629                **Example**16301631                ```python1632                from fastapi import FastAPI1633                from fastapi.responses import ORJSONResponse16341635                from .internal import old_api16361637                app = FastAPI()16381639                app.include_router(1640                    old_api.router,1641                    default_response_class=ORJSONResponse,1642                )1643                ```1644                """1645            ),1646        ] = Default(JSONResponse),1647        callbacks: Annotated[1648            list[BaseRoute] | None,1649            Doc(1650                """1651                List of *path operations* that will be used as OpenAPI callbacks.16521653                This is only for OpenAPI documentation, the callbacks won't be used1654                directly.16551656                It will be added to the generated OpenAPI (e.g. visible at `/docs`).16571658                Read more about it in the1659                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).1660                """1661            ),1662        ] = None,1663        generate_unique_id_function: Annotated[1664            Callable[[routing.APIRoute], str],1665            Doc(1666                """1667                Customize the function used to generate unique IDs for the *path1668                operations* shown in the generated OpenAPI.16691670                This is particularly useful when automatically generating clients or1671                SDKs for your API.16721673                Read more about it in the1674                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).1675                """1676            ),1677        ] = Default(generate_unique_id),1678    ) -> None:1679        """1680        Include an `APIRouter` in the same app.16811682        Read more about it in the1683        [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).16841685        ## Example16861687        ```python1688        from fastapi import FastAPI16891690        from .users import users_router16911692        app = FastAPI()16931694        app.include_router(users_router)1695        ```1696        """1697        self.router.include_router(1698            router,1699            prefix=prefix,1700            tags=tags,1701            dependencies=dependencies,1702            responses=responses,1703            deprecated=deprecated,1704            include_in_schema=include_in_schema,1705            default_response_class=default_response_class,1706            callbacks=callbacks,1707            generate_unique_id_function=generate_unique_id_function,1708        )17091710    def get(1711        self,1712        path: Annotated[1713            str,1714            Doc(1715                """1716                The URL path to be used for this *path operation*.17171718                For example, in `http://example.com/items`, the path is `/items`.1719                """1720            ),1721        ],1722        *,1723        response_model: Annotated[1724            Any,1725            Doc(1726                """1727                The type to use for the response.17281729                It could be any valid Pydantic *field* type. So, it doesn't have to1730                be a Pydantic model, it could be other things, like a `list`, `dict`,1731                etc.17321733                It will be used for:17341735                * Documentation: the generated OpenAPI (and the UI at `/docs`) will1736                    show it as the response (JSON Schema).1737                * Serialization: you could return an arbitrary object and the1738                    `response_model` would be used to serialize that object into the1739                    corresponding JSON.1740                * Filtering: the JSON sent to the client will only contain the data1741                    (fields) defined in the `response_model`. If you returned an object1742                    that contains an attribute `password` but the `response_model` does1743                    not include that field, the JSON sent to the client would not have1744                    that `password`.1745                * Validation: whatever you return will be serialized with the1746                    `response_model`, converting any data as necessary to generate the1747                    corresponding JSON. But if the data in the object returned is not1748                    valid, that would mean a violation of the contract with the client,1749                    so it's an error from the API developer. So, FastAPI will raise an1750                    error and return a 500 error code (Internal Server Error).17511752                Read more about it in the1753                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).1754                """1755            ),1756        ] = Default(None),1757        status_code: Annotated[1758            int | None,1759            Doc(1760                """1761                The default status code to be used for the response.17621763                You could override the status code by returning a response directly.17641765                Read more about it in the1766                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).1767                """1768            ),1769        ] = None,1770        tags: Annotated[1771            list[str | Enum] | None,1772            Doc(1773                """1774                A list of tags to be applied to the *path operation*.17751776                It will be added to the generated OpenAPI (e.g. visible at `/docs`).17771778                Read more about it in the1779                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).1780                """1781            ),1782        ] = None,1783        dependencies: Annotated[1784            Sequence[Depends] | None,1785            Doc(1786                """1787                A list of dependencies (using `Depends()`) to be applied to the1788                *path operation*.17891790                Read more about it in the1791                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).1792                """1793            ),1794        ] = None,1795        summary: Annotated[1796            str | None,1797            Doc(1798                """1799                A summary for the *path operation*.18001801                It will be added to the generated OpenAPI (e.g. visible at `/docs`).18021803                Read more about it in the1804                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).1805                """1806            ),1807        ] = None,1808        description: Annotated[1809            str | None,1810            Doc(1811                """1812                A description for the *path operation*.18131814                If not provided, it will be extracted automatically from the docstring1815                of the *path operation function*.18161817                It can contain Markdown.18181819                It will be added to the generated OpenAPI (e.g. visible at `/docs`).18201821                Read more about it in the1822                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).1823                """1824            ),1825        ] = None,1826        response_description: Annotated[1827            str,1828            Doc(1829                """1830                The description for the default response.18311832                It will be added to the generated OpenAPI (e.g. visible at `/docs`).1833                """1834            ),1835        ] = "Successful Response",1836        responses: Annotated[1837            dict[int | str, dict[str, Any]] | None,1838            Doc(1839                """1840                Additional responses that could be returned by this *path operation*.18411842                It will be added to the generated OpenAPI (e.g. visible at `/docs`).1843                """1844            ),1845        ] = None,1846        deprecated: Annotated[1847            bool | None,1848            Doc(1849                """1850                Mark this *path operation* as deprecated.18511852                It will be added to the generated OpenAPI (e.g. visible at `/docs`).1853                """1854            ),1855        ] = None,1856        operation_id: Annotated[1857            str | None,1858            Doc(1859                """1860                Custom operation ID to be used by this *path operation*.18611862                By default, it is generated automatically.18631864                If you provide a custom operation ID, you need to make sure it is1865                unique for the whole API.18661867                You can customize the1868                operation ID generation with the parameter1869                `generate_unique_id_function` in the `FastAPI` class.18701871                Read more about it in the1872                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).1873                """1874            ),1875        ] = None,1876        response_model_include: Annotated[1877            IncEx | None,1878            Doc(1879                """1880                Configuration passed to Pydantic to include only certain fields in the1881                response data.18821883                Read more about it in the1884                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).1885                """1886            ),1887        ] = None,1888        response_model_exclude: Annotated[1889            IncEx | None,1890            Doc(1891                """1892                Configuration passed to Pydantic to exclude certain fields in the1893                response data.18941895                Read more about it in the1896                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).1897                """1898            ),1899        ] = None,1900        response_model_by_alias: Annotated[1901            bool,1902            Doc(1903                """1904                Configuration passed to Pydantic to define if the response model1905                should be serialized by alias when an alias is used.19061907                Read more about it in the1908                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).1909                """1910            ),1911        ] = True,1912        response_model_exclude_unset: Annotated[1913            bool,1914            Doc(1915                """1916                Configuration passed to Pydantic to define if the response data1917                should have all the fields, including the ones that were not set and1918                have their default values. This is different from1919                `response_model_exclude_defaults` in that if the fields are set,1920                they will be included in the response, even if the value is the same1921                as the default.19221923                When `True`, default values are omitted from the response.19241925                Read more about it in the1926                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).1927                """1928            ),1929        ] = False,1930        response_model_exclude_defaults: Annotated[1931            bool,1932            Doc(1933                """1934                Configuration passed to Pydantic to define if the response data1935                should have all the fields, including the ones that have the same value1936                as the default. This is different from `response_model_exclude_unset`1937                in that if the fields are set but contain the same default values,1938                they will be excluded from the response.19391940                When `True`, default values are omitted from the response.19411942                Read more about it in the1943                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).1944                """1945            ),1946        ] = False,1947        response_model_exclude_none: Annotated[1948            bool,1949            Doc(1950                """1951                Configuration passed to Pydantic to define if the response data should1952                exclude fields set to `None`.19531954                This is much simpler (less smart) than `response_model_exclude_unset`1955                and `response_model_exclude_defaults`. You probably want to use one of1956                those two instead of this one, as those allow returning `None` values1957                when it makes sense.19581959                Read more about it in the1960                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).1961                """1962            ),1963        ] = False,1964        include_in_schema: Annotated[1965            bool,1966            Doc(1967                """1968                Include this *path operation* in the generated OpenAPI schema.19691970                This affects the generated OpenAPI (e.g. visible at `/docs`).19711972                Read more about it in the1973                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).1974                """1975            ),1976        ] = True,1977        response_class: Annotated[1978            type[Response],1979            Doc(1980                """1981                Response class to be used for this *path operation*.19821983                This will not be used if you return a response directly.19841985                Read more about it in the1986                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).1987                """1988            ),1989        ] = Default(JSONResponse),1990        name: Annotated[1991            str | None,1992            Doc(1993                """1994                Name for this *path operation*. Only used internally.1995                """1996            ),1997        ] = None,1998        callbacks: Annotated[1999            list[BaseRoute] | None,2000            Doc(

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.

Generated by searchcode.com · powered by code_get_file + code_get_findings