fastapi API Reference
Full documentation for fastapi (0.141.1)
fastapi.APIRouter
Python Library Documentation: class APIRouter in module fastapi.routing
class APIRouter(starlette.routing.Router)
| APIRouter(*, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2BD0>, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E541B35F0>] = None, redirect_slashes: Annotated[bool, Doc("\n Whether to detect and redirect slashes in URLs when the client doesn't\n use the same format.\n ")] = True, default: Annotated[collections.abc.Callable[[collections.abc.MutableMapping[str, Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]] | None, Doc('\n Default function handler for this router. Used to handle\n 404 Not Found errors.\n ')] = None, dependency_overrides_provider: Annotated[Any | None, Doc("\n Only used internally by FastAPI to handle dependency overrides.\n\n You shouldn't need to use it. It normally points to the `FastAPI` app\n object.\n ")] = None, route_class: Annotated[type[fastapi.routing.APIRoute], Doc('\n Custom route (*path operation*) class to be used by this router.\n\n Read more about it in the\n [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).\n ')] = <class 'fastapi.routing.APIRoute'>, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, include_in_schema: Annotated[bool, Doc('\n To include (or not) all the *path operations* in this router in the\n generated OpenAPI.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C30>, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C60>) -> None
|
| `APIRouter` class, used to group *path operations*, for example to structure
| an app in multiple files. It would then be included in the `FastAPI` app, or
| in another `APIRouter` (ultimately included in the app).
|
| Read more about it in the
| [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
|
| @router.get("/users/", tags=["users"])
| async def read_users():
| return [{"username": "Rick"}, {"username": "Morty"}]
|
|
| app.include_router(router)
| ```
|
| Method resolution order:
| APIRouter
| starlette.routing.Router
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2BD0>, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E541B35F0>] = None, redirect_slashes: Annotated[bool, Doc("\n Whether to detect and redirect slashes in URLs when the client doesn't\n use the same format.\n ")] = True, default: Annotated[collections.abc.Callable[[collections.abc.MutableMapping[str, Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]] | None, Doc('\n Default function handler for this router. Used to handle\n 404 Not Found errors.\n ')] = None, dependency_overrides_provider: Annotated[Any | None, Doc("\n Only used internally by FastAPI to handle dependency overrides.\n\n You shouldn't need to use it. It normally points to the `FastAPI` app\n object.\n ")] = None, route_class: Annotated[type[fastapi.routing.APIRoute], Doc('\n Custom route (*path operation*) class to be used by this router.\n\n Read more about it in the\n [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).\n ')] = <class 'fastapi.routing.APIRoute'>, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, include_in_schema: Annotated[bool, Doc('\n To include (or not) all the *path operations* in this router in the\n generated OpenAPI.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C30>, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C60>) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| add_api_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D49E0>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: set[str] | list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4A10>, name: str | None = None, route_class_override: type[fastapi.routing.APIRoute] | None = None, callbacks: list[starlette.routing.BaseRoute] | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4A40>, strict_content_type: bool | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4A70>) -> None
|
| add_api_websocket_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], name: str | None = None, *, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None) -> None
|
| add_event_handler(self, event_type: str, func: collections.abc.Callable[[], typing.Any]) -> None
| Add an event handler function for startup or shutdown.
|
| This method is kept for backward compatibility after Starlette removed
| support for on_startup/on_shutdown handlers.
|
| Ref: https://github.com/Kludex/starlette/pull/3117
|
| add_route(self, path: str, endpoint: collections.abc.Callable[[starlette.requests.Request], collections.abc.Awaitable[starlette.responses.Response] | starlette.responses.Response], methods: collections.abc.Collection[str] | None = None, name: str | None = None, include_in_schema: bool = True) -> None
|
| add_websocket_route(self, path: str, endpoint: collections.abc.Callable[[starlette.websockets.WebSocket], collections.abc.Awaitable[None]], name: str | None = None) -> None
|
| api_route(self, path: str, *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4F50>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4F80>, name: str | None = None, callbacks: list[starlette.routing.BaseRoute] | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4FB0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| async app(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
|
| delete(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F30>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F60>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F90>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP DELETE operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
| @router.delete("/items/{item_id}")
| def delete_item(item_id: str):
| return {"message": "Item deleted"}
|
| app.include_router(router)
| ```
|
| frontend(self, path: Annotated[str, Doc('\n The URL path prefix where the frontend build should be served.\n ')], *, directory: Annotated[str | os.PathLike[str], Doc('\n The directory containing the static frontend build output.\n ')], fallback: Annotated[Optional[Literal['auto', 'index.html', '404.html']], Doc('\n The fallback file behavior for missing frontend paths.\n ')] = 'auto', check_dir: Annotated[Union[bool, Literal['auto']], Doc('\n Check that the frontend directory exists when the app is created. When\n set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is\n `"development"`, and check it otherwise. The `fastapi dev` command\n sets `FASTAPI_ENV` to `"development"` if it is not already set.\n ')] = 'auto') -> None
| Serve a static frontend build as low-priority routes.
|
| Use this for frontend tools that build static files into a directory,
| such as `dist`. **FastAPI** path operations are checked first, and
| the frontend files are checked only if no normal route matched.
|
| A typical project could look like this:
|
| ```text
| .
| ├── pyproject.toml
| ├── app
| │ ├── __init__.py
| │ └── main.py
| └── dist
| ├── index.html
| └── assets
| └── app.js
| ```
|
| Then in `app/main.py`:
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
| router.frontend("/", directory="dist")
| app.include_router(router)
| ```
|
| get(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D59A0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5A00>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5A30>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP GET operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
| @router.get("/items/")
| def read_items():
| return [{"name": "Empanada"}, {"name": "Arepa"}]
|
| app.include_router(router)
| ```
|
| async handle(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
|
| head(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7050>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7080>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D70B0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP HEAD operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.head("/items/", status_code=204)
| def get_items_headers(response: Response):
| response.headers["X-Cat-Dog"] = "Alone in the world"
|
| app.include_router(router)
| ```
|
| include_router(self, router: Annotated[ForwardRef('APIRouter'), Doc('The `APIRouter` to include.')], *, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5730>, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, include_in_schema: Annotated[bool, Doc('\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ')] = True, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5760>) -> None
| Include another `APIRouter` in the same current `APIRouter`.
|
| Read more about it in the
| [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| internal_router = APIRouter()
| users_router = APIRouter()
|
| @users_router.get("/users/")
| def read_users():
| return [{"name": "Rick"}, {"name": "Morty"}]
|
| internal_router.include_router(users_router)
| app.include_router(internal_router)
| ```
|
| matches(self, scope: collections.abc.MutableMapping[str, typing.Any]) -> tuple[starlette.routing.Match, collections.abc.MutableMapping[str, typing.Any]]
|
| on_event(self, event_type: Annotated[str, Doc('\n The type of event. `startup` or `shutdown`.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add an event handler for the router.
|
| `on_event` is deprecated, use `lifespan` event handlers instead.
|
| Read more about it in the
| [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
|
| options(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6FC0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6FF0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7020>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP OPTIONS operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
| @router.options("/items/")
| def get_item_options():
| return {"additions": ["Aji", "Guacamole"]}
|
| app.include_router(router)
| ```
|
| patch(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D70E0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7110>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7140>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PATCH operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.patch("/items/")
| def update_item(item: Item):
| return {"message": "Item updated in place"}
|
| app.include_router(router)
| ```
|
| post(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6EA0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6ED0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F00>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP POST operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.post("/items/")
| def create_item(item: Item):
| return {"message": "Item created"}
|
| app.include_router(router)
| ```
|
| put(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6E10>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6E40>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6E70>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PUT operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.put("/items/{item_id}")
| def replace_item(item_id: str, item: Item):
| return {"message": "Item replaced", "id": item_id}
|
| app.include_router(router)
| ```
|
| route(self, path: str, methods: collections.abc.Collection[str] | None = None, name: str | None = None, include_in_schema: bool = True) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| trace(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7170>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D71A0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D71D0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP TRACE operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.trace("/items/{item_id}")
| def trace_item(item_id: str):
| return None
|
| app.include_router(router)
| ```
|
| websocket(self, path: Annotated[str, Doc('\n WebSocket path.\n ')], name: Annotated[str | None, Doc('\n A name for the WebSocket. Only used internally.\n ')] = None, *, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n ')] = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Decorate a WebSocket function.
|
| Read more about it in the
| [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| **Example**
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI, WebSocket
|
| app = FastAPI()
| router = APIRouter()
|
| @router.websocket("/ws")
| async def websocket_endpoint(websocket: WebSocket):
| await websocket.accept()
| while True:
| data = await websocket.receive_text()
| await websocket.send_text(f"Message text was: {data}")
|
| app.include_router(router)
| ```
|
| websocket_route(self, path: str, name: str | None = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.routing.Router:
|
| async __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| The main entry point to the Router class.
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| host(self, host: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| async lifespan(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| Handle ASGI lifespan messages, which allows us to manage application
| startup and shutdown events.
|
| mount(self, path: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| async not_found(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
|
| url_path_for(self, name: 'str', /, **path_params: 'Any') -> 'URLPath'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.routing.Router:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from starlette.routing.Router:
|
| __hash__ = None
fastapi.BackgroundTasks
Python Library Documentation: class BackgroundTasks in module fastapi.background
class BackgroundTasks(starlette.background.BackgroundTasks)
| BackgroundTasks(tasks: 'Sequence[BackgroundTask] | None' = None)
|
| A collection of background tasks that will be called after a response has been
| sent to the client.
|
| Read more about it in the
| [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
|
| ## Example
|
| ```python
| from fastapi import BackgroundTasks, FastAPI
|
| app = FastAPI()
|
|
| def write_notification(email: str, message=""):
| with open("log.txt", mode="w") as email_file:
| content = f"notification for {email}: {message}"
| email_file.write(content)
|
|
| @app.post("/send-notification/{email}")
| async def send_notification(email: str, background_tasks: BackgroundTasks):
| background_tasks.add_task(write_notification, email, message="some notification")
| return {"message": "Notification sent in the background"}
| ```
|
| Method resolution order:
| BackgroundTasks
| starlette.background.BackgroundTasks
| starlette.background.BackgroundTask
| builtins.object
|
| Methods defined here:
|
| add_task(self, func: Annotated[collections.abc.Callable[~P, Any], Doc('\n The function to call after the response is sent.\n\n It can be a regular `def` function or an `async def` function.\n ')], *args: P.args, **kwargs: P.kwargs) -> None
| Add a function to be called in the background after the response is sent.
|
| Read more about it in the
| [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.background.BackgroundTasks:
|
| async __call__(self) -> 'None'
| Call self as a function.
|
| __init__(self, tasks: 'Sequence[BackgroundTask] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.background.BackgroundTask:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
fastapi.Body
Python Library Documentation: function Body in module fastapi.param_functions
Body(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, embed: Annotated[bool | None, Doc('\n When `embed` is `True`, the parameter will be expected in a JSON body as a\n key instead of being the JSON body itself.\n\n This happens automatically when more than one `Body` parameter is declared.\n\n Read more about it in the\n [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter).\n ')] = None, media_type: Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'application/json', alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410E570>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410E660>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410E780>]) -> Any
fastapi.Cookie
Python Library Documentation: function Cookie in module fastapi.param_functions
Cookie(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410E060>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410E150>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410E270>]) -> Any
fastapi.Depends
Python Library Documentation: function Depends in module fastapi.param_functions
Depends(dependency: Annotated[collections.abc.Callable[..., Any] | None, Doc('\n A "dependable" callable (like a function).\n\n Don\'t call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n ')] = None, *, use_cache: Annotated[bool, Doc('\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n ')] = True, scope: Annotated[Optional[Literal['function', 'request']], Doc('\n Mainly for dependencies with `yield`, define when the dependency function\n should start (the code before `yield`) and when it should end (the code\n after `yield`).\n\n * `"function"`: start the dependency before the *path operation function*\n that handles the request, end the dependency after the *path operation\n function* ends, but **before** the response is sent back to the client.\n So, the dependency function will be executed **around** the *path operation\n **function***.\n * `"request"`: start the dependency before the *path operation function*\n that handles the request (similar to when using `"function"`), but end\n **after** the response is sent back to the client. So, the dependency\n function will be executed **around** the **request** and response cycle.\n\n Read more about it in the\n [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)\n ')] = None) -> Any
Declare a FastAPI dependency.
It takes a single "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you.
Read more about it in the
[FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).
**Example**
```python
from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons
```
fastapi.FastAPI
Python Library Documentation: class FastAPI in module fastapi.applications
class FastAPI(starlette.applications.Starlette)
| FastAPI(*, debug: Annotated[bool, Doc('\n Boolean indicating if debug tracebacks should be returned on server\n errors.\n\n Read more in the\n [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette).\n ')] = False, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E542020F0>] = None, title: Annotated[str, Doc('\n The title of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(title="ChimichangApp")\n ```\n ')] = 'FastAPI', summary: Annotated[str | None, Doc('\n A short summary of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(summary="Deadpond\'s favorite app. Nuff said.")\n ```\n ')] = None, description: Annotated[str, Doc('\n A description of the API. Supports Markdown (using\n [CommonMark syntax](https://commonmark.org/)).\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n description="""\n ChimichangApp API helps you do awesome stuff. 🚀\n\n ## Items\n\n You can **read items**.\n\n ## Users\n\n You will be able to:\n\n * **Create users** (_not implemented_).\n * **Read users** (_not implemented_).\n\n """\n )\n ```\n ')] = '', version: Annotated[str, Doc('\n The version of the API.\n\n **Note** This is the version of your application, not the version of\n the OpenAPI specification nor the version of FastAPI being used.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(version="0.0.1")\n ```\n ')] = '0.1.0', openapi_url: Annotated[str | None, Doc('\n The URL where the OpenAPI schema will be served from.\n\n If you set it to `None`, no OpenAPI schema will be served publicly, and\n the default automatic endpoints `/docs` and `/redoc` will also be\n disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(openapi_url="/api/v1/openapi.json")\n ```\n ')] = '/openapi.json', openapi_tags: Annotated[list[dict[str, Any]] | None, Doc('\n A list of tags used by OpenAPI, these are the same `tags` you can set\n in the *path operations*, like:\n\n * `@app.get("/users/", tags=["users"])`\n * `@app.get("/items/", tags=["items"])`\n\n The order of the tags can be used to specify the order shown in\n tools like Swagger UI, used in the automatic path `/docs`.\n\n It\'s not required to specify all the tags used.\n\n The tags that are not declared MAY be organized randomly or based\n on the tools\' logic. Each tag name in the list MUST be unique.\n\n The value of each item is a `dict` containing:\n\n * `name`: The name of the tag.\n * `description`: A short description of the tag.\n [CommonMark syntax](https://commonmark.org/) MAY be used for rich\n text representation.\n * `externalDocs`: Additional external documentation for this tag. If\n provided, it would contain a `dict` with:\n * `description`: A short description of the target documentation.\n [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `url`: The URL for the target documentation. Value MUST be in\n the form of a URL.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n tags_metadata = [\n {\n "name": "users",\n "description": "Operations with users. The **login** logic is also here.",\n },\n {\n "name": "items",\n "description": "Manage items. So _fancy_ they have their own docs.",\n "externalDocs": {\n "description": "Items external docs",\n "url": "https://fastapi.tiangolo.com/",\n },\n },\n ]\n\n app = FastAPI(openapi_tags=tags_metadata)\n ```\n ')] = None, servers: Annotated[list[dict[str, str | Any]] | None, Doc('\n A `list` of `dict`s with connectivity information to a target server.\n\n You would use it, for example, if your application is served from\n different domains and you want to use the same Swagger UI in the\n browser to interact with each of them (instead of having multiple\n browser tabs open). Or if you want to leave fixed the possible URLs.\n\n If the servers `list` is not provided, or is an empty `list`, the\n `servers` property in the generated OpenAPI will be:\n\n * a `dict` with a `url` value of the application\'s mounting point\n (`root_path`) if it\'s different from `/`.\n * otherwise, the `servers` property will be omitted from the OpenAPI\n schema.\n\n Each item in the `list` is a `dict` containing:\n\n * `url`: A URL to the target host. This URL supports Server Variables\n and MAY be relative, to indicate that the host location is relative\n to the location where the OpenAPI document is being served. Variable\n substitutions will be made when a variable is named in `{`brackets`}`.\n * `description`: An optional string describing the host designated by\n the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `variables`: A `dict` between a variable name and its value. The value\n is used for substitution in the server\'s URL template.\n\n Read more in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n servers=[\n {"url": "https://stag.example.com", "description": "Staging environment"},\n {"url": "https://prod.example.com", "description": "Production environment"},\n ]\n )\n ```\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of global dependencies, they will be applied to each\n *path operation*, including in sub-routers.\n\n Read more about it in the\n [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import func_dep_1, func_dep_2\n\n app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])\n ```\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n app = FastAPI(default_response_class=ORJSONResponse)\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E51783EC0>, redirect_slashes: Annotated[bool, Doc('\n Whether to detect and redirect slashes in URLs when the client doesn\'t\n use the same format.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(redirect_slashes=True) # the default\n\n @app.get("/items/")\n async def read_items():\n return [{"item_id": "Foo"}]\n ```\n\n With this app, if a client goes to `/items` (without a trailing slash),\n they will be automatically redirected with an HTTP status code of 307\n to `/items/`.\n ')] = True, docs_url: Annotated[str | None, Doc('\n The path to the automatic interactive API documentation.\n It is handled in the browser by Swagger UI.\n\n The default URL is `/docs`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url=None)\n ```\n ')] = '/docs', redoc_url: Annotated[str | None, Doc('\n The path to the alternative automatic interactive API documentation\n provided by ReDoc.\n\n The default URL is `/redoc`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")\n ```\n ')] = '/redoc', swagger_ui_oauth2_redirect_url: Annotated[str | None, Doc('\n The OAuth2 redirect endpoint for the Swagger UI.\n\n By default it is `/docs/oauth2-redirect`.\n\n This is only used if you use OAuth2 (with the "Authorize" button)\n with Swagger UI.\n ')] = '/docs/oauth2-redirect', swagger_ui_init_oauth: Annotated[dict[str, Any] | None, Doc('\n OAuth2 configuration for the Swagger UI, by default shown at `/docs`.\n\n Read more about the available configuration options in the\n [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).\n ')] = None, middleware: Annotated[collections.abc.Sequence[starlette.middleware.Middleware] | None, Doc('\n List of middleware to be added when creating the application.\n\n In FastAPI you would normally do this with `app.add_middleware()`\n instead.\n\n Read more in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n ')] = None, exception_handlers: Annotated[dict[int | type[Exception], collections.abc.Callable[[starlette.requests.Request, Any], collections.abc.Coroutine[Any, Any, starlette.responses.Response]]] | None, Doc('\n A dictionary with handlers for exceptions.\n\n In FastAPI, you would normally use the decorator\n `@app.exception_handler()`.\n\n Read more in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n ')] = None, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, terms_of_service: Annotated[str | None, Doc('\n A URL to the Terms of Service for your API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(terms_of_service="http://example.com/terms/")\n ```\n ')] = None, contact: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the contact information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) The name of the contact person/organization.\n * `url`: (`str`) A URL pointing to the contact information. MUST be in\n the format of a URL.\n * `email`: (`str`) The email address of the contact person/organization.\n MUST be in the format of an email address.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n contact={\n "name": "Deadpoolio the Amazing",\n "url": "http://x-force.example.com/contact/",\n "email": "dp@x-force.example.com",\n }\n )\n ```\n ')] = None, license_info: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the license information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The\n license name used for the API.\n * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression\n for the API. The `identifier` field is mutually exclusive of the `url`\n field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.\n * `url`: (`str`) A URL to the license used for the API. This MUST be\n the format of a URL.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n license_info={\n "name": "Apache 2.0",\n "url": "https://www.apache.org/licenses/LICENSE-2.0.html",\n }\n )\n ```\n ')] = None, openapi_prefix: Annotated[str, Doc('\n A URL prefix for the OpenAPI URL.\n '), <typing_extensions.deprecated object at 0x0000024E54203620>] = '', root_path: Annotated[str, Doc('\n A path prefix handled by a proxy that is not seen by the application\n but is seen by external clients, which affects things like Swagger UI.\n\n Read more about it at the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path="/api/v1")\n ```\n ')] = '', root_path_in_servers: Annotated[bool, Doc('\n To disable automatically generating the URLs in the `servers` field\n in the autogenerated OpenAPI using the `root_path`.\n\n Read more about it in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path_in_servers=False)\n ```\n ')] = True, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, webhooks: Annotated[fastapi.routing.APIRouter | None, Doc("\n Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't\n depend on specific *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n ")] = None, deprecated: Annotated[bool | None, Doc("\n Mark all *path operations* as deprecated. You probably don't need it,\n but it's available.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).\n ")] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) all the *path operations* in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ")] = True, swagger_ui_parameters: Annotated[dict[str, Any] | None, Doc('\n Parameters to configure Swagger UI, the autogenerated interactive API\n documentation (by default at `/docs`).\n\n Read more about it in the\n [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54201FD0>, separate_input_output_schemas: Annotated[bool, Doc("\n Whether to generate separate OpenAPI schemas for request body and\n response body when the results would be more precise.\n\n This is particularly useful when automatically generating clients.\n\n For example, if you have a model like:\n\n ```python\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n tags: list[str] = []\n ```\n\n When `Item` is used for input, a request body, `tags` is not required,\n the client doesn't have to provide it.\n\n But when using `Item` for output, for a response body, `tags` is always\n available because it has a default value, even if it's just an empty\n list. So, the client should be able to always expect it.\n\n In this case, there would be two different schemas, one for input and\n another one for output.\n\n Read more about it in the\n [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)\n ")] = True, openapi_external_docs: Annotated[dict[str, Any] | None, Doc('\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n\n * `description`: A brief description of the external documentation.\n * `url`: The URL pointing to the external documentation. The value **MUST**\n be a valid URL format.\n\n **Example**:\n\n ```python\n from fastapi import FastAPI\n\n external_docs = {\n "description": "Detailed API Reference",\n "url": "https://example.com/api-docs",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n ```\n ')] = None, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = True, **extra: Annotated[Any, Doc('\n Extra keyword arguments to be stored in the app, not used by FastAPI\n anywhere.\n ')]) -> None
|
| `FastAPI` app class, the main entrypoint to use FastAPI.
|
| Read more in the
| [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
| ```
|
| Method resolution order:
| FastAPI
| starlette.applications.Starlette
| builtins.object
|
| Methods defined here:
|
| async __call__(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
| Call self as a function.
|
| __init__(self: ~AppType, *, debug: Annotated[bool, Doc('\n Boolean indicating if debug tracebacks should be returned on server\n errors.\n\n Read more in the\n [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette).\n ')] = False, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E542020F0>] = None, title: Annotated[str, Doc('\n The title of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(title="ChimichangApp")\n ```\n ')] = 'FastAPI', summary: Annotated[str | None, Doc('\n A short summary of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(summary="Deadpond\'s favorite app. Nuff said.")\n ```\n ')] = None, description: Annotated[str, Doc('\n A description of the API. Supports Markdown (using\n [CommonMark syntax](https://commonmark.org/)).\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n description="""\n ChimichangApp API helps you do awesome stuff. 🚀\n\n ## Items\n\n You can **read items**.\n\n ## Users\n\n You will be able to:\n\n * **Create users** (_not implemented_).\n * **Read users** (_not implemented_).\n\n """\n )\n ```\n ')] = '', version: Annotated[str, Doc('\n The version of the API.\n\n **Note** This is the version of your application, not the version of\n the OpenAPI specification nor the version of FastAPI being used.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(version="0.0.1")\n ```\n ')] = '0.1.0', openapi_url: Annotated[str | None, Doc('\n The URL where the OpenAPI schema will be served from.\n\n If you set it to `None`, no OpenAPI schema will be served publicly, and\n the default automatic endpoints `/docs` and `/redoc` will also be\n disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(openapi_url="/api/v1/openapi.json")\n ```\n ')] = '/openapi.json', openapi_tags: Annotated[list[dict[str, Any]] | None, Doc('\n A list of tags used by OpenAPI, these are the same `tags` you can set\n in the *path operations*, like:\n\n * `@app.get("/users/", tags=["users"])`\n * `@app.get("/items/", tags=["items"])`\n\n The order of the tags can be used to specify the order shown in\n tools like Swagger UI, used in the automatic path `/docs`.\n\n It\'s not required to specify all the tags used.\n\n The tags that are not declared MAY be organized randomly or based\n on the tools\' logic. Each tag name in the list MUST be unique.\n\n The value of each item is a `dict` containing:\n\n * `name`: The name of the tag.\n * `description`: A short description of the tag.\n [CommonMark syntax](https://commonmark.org/) MAY be used for rich\n text representation.\n * `externalDocs`: Additional external documentation for this tag. If\n provided, it would contain a `dict` with:\n * `description`: A short description of the target documentation.\n [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `url`: The URL for the target documentation. Value MUST be in\n the form of a URL.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n tags_metadata = [\n {\n "name": "users",\n "description": "Operations with users. The **login** logic is also here.",\n },\n {\n "name": "items",\n "description": "Manage items. So _fancy_ they have their own docs.",\n "externalDocs": {\n "description": "Items external docs",\n "url": "https://fastapi.tiangolo.com/",\n },\n },\n ]\n\n app = FastAPI(openapi_tags=tags_metadata)\n ```\n ')] = None, servers: Annotated[list[dict[str, str | Any]] | None, Doc('\n A `list` of `dict`s with connectivity information to a target server.\n\n You would use it, for example, if your application is served from\n different domains and you want to use the same Swagger UI in the\n browser to interact with each of them (instead of having multiple\n browser tabs open). Or if you want to leave fixed the possible URLs.\n\n If the servers `list` is not provided, or is an empty `list`, the\n `servers` property in the generated OpenAPI will be:\n\n * a `dict` with a `url` value of the application\'s mounting point\n (`root_path`) if it\'s different from `/`.\n * otherwise, the `servers` property will be omitted from the OpenAPI\n schema.\n\n Each item in the `list` is a `dict` containing:\n\n * `url`: A URL to the target host. This URL supports Server Variables\n and MAY be relative, to indicate that the host location is relative\n to the location where the OpenAPI document is being served. Variable\n substitutions will be made when a variable is named in `{`brackets`}`.\n * `description`: An optional string describing the host designated by\n the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `variables`: A `dict` between a variable name and its value. The value\n is used for substitution in the server\'s URL template.\n\n Read more in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n servers=[\n {"url": "https://stag.example.com", "description": "Staging environment"},\n {"url": "https://prod.example.com", "description": "Production environment"},\n ]\n )\n ```\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of global dependencies, they will be applied to each\n *path operation*, including in sub-routers.\n\n Read more about it in the\n [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import func_dep_1, func_dep_2\n\n app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])\n ```\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n app = FastAPI(default_response_class=ORJSONResponse)\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E51783EC0>, redirect_slashes: Annotated[bool, Doc('\n Whether to detect and redirect slashes in URLs when the client doesn\'t\n use the same format.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(redirect_slashes=True) # the default\n\n @app.get("/items/")\n async def read_items():\n return [{"item_id": "Foo"}]\n ```\n\n With this app, if a client goes to `/items` (without a trailing slash),\n they will be automatically redirected with an HTTP status code of 307\n to `/items/`.\n ')] = True, docs_url: Annotated[str | None, Doc('\n The path to the automatic interactive API documentation.\n It is handled in the browser by Swagger UI.\n\n The default URL is `/docs`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url=None)\n ```\n ')] = '/docs', redoc_url: Annotated[str | None, Doc('\n The path to the alternative automatic interactive API documentation\n provided by ReDoc.\n\n The default URL is `/redoc`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")\n ```\n ')] = '/redoc', swagger_ui_oauth2_redirect_url: Annotated[str | None, Doc('\n The OAuth2 redirect endpoint for the Swagger UI.\n\n By default it is `/docs/oauth2-redirect`.\n\n This is only used if you use OAuth2 (with the "Authorize" button)\n with Swagger UI.\n ')] = '/docs/oauth2-redirect', swagger_ui_init_oauth: Annotated[dict[str, Any] | None, Doc('\n OAuth2 configuration for the Swagger UI, by default shown at `/docs`.\n\n Read more about the available configuration options in the\n [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).\n ')] = None, middleware: Annotated[collections.abc.Sequence[starlette.middleware.Middleware] | None, Doc('\n List of middleware to be added when creating the application.\n\n In FastAPI you would normally do this with `app.add_middleware()`\n instead.\n\n Read more in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n ')] = None, exception_handlers: Annotated[dict[int | type[Exception], collections.abc.Callable[[starlette.requests.Request, Any], collections.abc.Coroutine[Any, Any, starlette.responses.Response]]] | None, Doc('\n A dictionary with handlers for exceptions.\n\n In FastAPI, you would normally use the decorator\n `@app.exception_handler()`.\n\n Read more in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n ')] = None, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, terms_of_service: Annotated[str | None, Doc('\n A URL to the Terms of Service for your API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(terms_of_service="http://example.com/terms/")\n ```\n ')] = None, contact: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the contact information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) The name of the contact person/organization.\n * `url`: (`str`) A URL pointing to the contact information. MUST be in\n the format of a URL.\n * `email`: (`str`) The email address of the contact person/organization.\n MUST be in the format of an email address.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n contact={\n "name": "Deadpoolio the Amazing",\n "url": "http://x-force.example.com/contact/",\n "email": "dp@x-force.example.com",\n }\n )\n ```\n ')] = None, license_info: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the license information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The\n license name used for the API.\n * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression\n for the API. The `identifier` field is mutually exclusive of the `url`\n field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.\n * `url`: (`str`) A URL to the license used for the API. This MUST be\n the format of a URL.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n license_info={\n "name": "Apache 2.0",\n "url": "https://www.apache.org/licenses/LICENSE-2.0.html",\n }\n )\n ```\n ')] = None, openapi_prefix: Annotated[str, Doc('\n A URL prefix for the OpenAPI URL.\n '), <typing_extensions.deprecated object at 0x0000024E54203620>] = '', root_path: Annotated[str, Doc('\n A path prefix handled by a proxy that is not seen by the application\n but is seen by external clients, which affects things like Swagger UI.\n\n Read more about it at the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path="/api/v1")\n ```\n ')] = '', root_path_in_servers: Annotated[bool, Doc('\n To disable automatically generating the URLs in the `servers` field\n in the autogenerated OpenAPI using the `root_path`.\n\n Read more about it in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path_in_servers=False)\n ```\n ')] = True, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, webhooks: Annotated[fastapi.routing.APIRouter | None, Doc("\n Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't\n depend on specific *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n ")] = None, deprecated: Annotated[bool | None, Doc("\n Mark all *path operations* as deprecated. You probably don't need it,\n but it's available.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).\n ")] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) all the *path operations* in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ")] = True, swagger_ui_parameters: Annotated[dict[str, Any] | None, Doc('\n Parameters to configure Swagger UI, the autogenerated interactive API\n documentation (by default at `/docs`).\n\n Read more about it in the\n [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54201FD0>, separate_input_output_schemas: Annotated[bool, Doc("\n Whether to generate separate OpenAPI schemas for request body and\n response body when the results would be more precise.\n\n This is particularly useful when automatically generating clients.\n\n For example, if you have a model like:\n\n ```python\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n tags: list[str] = []\n ```\n\n When `Item` is used for input, a request body, `tags` is not required,\n the client doesn't have to provide it.\n\n But when using `Item` for output, for a response body, `tags` is always\n available because it has a default value, even if it's just an empty\n list. So, the client should be able to always expect it.\n\n In this case, there would be two different schemas, one for input and\n another one for output.\n\n Read more about it in the\n [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)\n ")] = True, openapi_external_docs: Annotated[dict[str, Any] | None, Doc('\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n\n * `description`: A brief description of the external documentation.\n * `url`: The URL pointing to the external documentation. The value **MUST**\n be a valid URL format.\n\n **Example**:\n\n ```python\n from fastapi import FastAPI\n\n external_docs = {\n "description": "Detailed API Reference",\n "url": "https://example.com/api-docs",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n ```\n ')] = None, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = True, **extra: Annotated[Any, Doc('\n Extra keyword arguments to be stored in the app, not used by FastAPI\n anywhere.\n ')]) -> None
| Initializes the application.
|
| Parameters:
| debug: Boolean indicating if debug tracebacks should be returned on errors.
| routes: A list of routes to serve incoming HTTP and WebSocket requests.
| middleware: A list of middleware to run for every request. A starlette
| application will always automatically include two middleware classes.
| `ServerErrorMiddleware` is added as the very outermost middleware, to handle
| any uncaught errors occurring anywhere in the entire stack.
| `ExceptionMiddleware` is added as the very innermost middleware, to deal
| with handled exception cases occurring in the routing or endpoints.
| exception_handlers: A mapping of either integer status codes,
| or exception class types onto callables which handle the exceptions.
| Exception handler callables should be of the form
| `handler(request, exc) -> response` and may be either standard functions, or
| async functions.
| lifespan: A lifespan context function, which can be used to perform
| startup and shutdown tasks. This is a newer style that replaces the
| `on_startup` and `on_shutdown` handlers. Use one or the other, not both.
|
| add_api_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54203F80>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54203FB0>, name: str | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54203FE0>) -> None
|
| add_api_websocket_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], name: str | None = None, *, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None) -> None
|
| api_route(self, path: str, *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E542103B0>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210410>, name: str | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210440>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| build_middleware_stack(self) -> collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]]
|
| delete(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210EC0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210EF0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210F20>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP DELETE operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.delete("/items/{item_id}")
| def delete_item(item_id: str):
| return {"message": "Item deleted"}
| ```
|
| exception_handler(self, exc_class_or_status_code: Annotated[int | type[Exception], Doc('\n The Exception class this would handle, or a status code.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add an exception handler to the app.
|
| Read more about it in the
| [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI, Request
| from fastapi.responses import JSONResponse
|
|
| class UnicornException(Exception):
| def __init__(self, name: str):
| self.name = name
|
|
| app = FastAPI()
|
|
| @app.exception_handler(UnicornException)
| async def unicorn_exception_handler(request: Request, exc: UnicornException):
| return JSONResponse(
| status_code=418,
| content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
| )
| ```
|
| frontend(self, path: Annotated[str, Doc('\n The URL path prefix where the frontend build should be served.\n ')], *, directory: Annotated[str | os.PathLike[str], Doc('\n The directory containing the static frontend build output.\n ')], fallback: Annotated[Optional[Literal['auto', 'index.html', '404.html']], Doc('\n The fallback file behavior for missing frontend paths.\n ')] = 'auto', check_dir: Annotated[Union[bool, Literal['auto']], Doc('\n Check that the frontend directory exists when the app is created. When\n set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is\n `"development"`, and check it otherwise. The `fastapi dev` command\n sets `FASTAPI_ENV` to `"development"` if it is not already set.\n ')] = 'auto') -> None
| Serve a static frontend build as low-priority routes.
|
| Use this for frontend tools that build static files into a directory,
| such as `dist`. **FastAPI** path operations are checked first, and
| the frontend files are checked only if no normal route matched.
|
| A typical project could look like this:
|
| ```text
| .
| ├── pyproject.toml
| ├── app
| │ ├── __init__.py
| │ └── main.py
| └── dist
| ├── index.html
| └── assets
| └── app.js
| ```
|
| Then in `app/main.py`:
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
| app.frontend("/", directory="dist")
| ```
|
| get(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210D10>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210D40>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210D70>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP GET operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.get("/items/")
| def read_items():
| return [{"name": "Empanada"}, {"name": "Arepa"}]
| ```
|
| head(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210FE0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211010>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211040>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP HEAD operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI, Response
|
| app = FastAPI()
|
| @app.head("/items/", status_code=204)
| def get_items_headers(response: Response):
| response.headers["X-Cat-Dog"] = "Alone in the world"
| ```
|
| include_router(self, router: Annotated[fastapi.routing.APIRouter, Doc('The `APIRouter` to include.')], *, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import get_token_header\n from .internal import admin\n\n app = FastAPI()\n\n app.include_router(\n admin.router,\n dependencies=[Depends(get_token_header)],\n )\n ```\n ')] = None, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all the *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n deprecated=True,\n )\n ```\n ')] = None, include_in_schema: Annotated[bool, Doc('\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n include_in_schema=False,\n )\n ```\n ')] = True, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n Default response class to be used for the *path operations* in this\n router.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n default_response_class=ORJSONResponse,\n )\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210800>, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210860>) -> None
| Include an `APIRouter` in the same app.
|
| Read more about it in the
| [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| from .users import users_router
|
| app = FastAPI()
|
| app.include_router(users_router)
| ```
|
| middleware(self, middleware_type: Annotated[str, Doc('\n The type of middleware. Currently only supports `http`.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a middleware to the application.
|
| Read more about it in the
| [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
|
| ## Example
|
| ```python
| import time
| from typing import Awaitable, Callable
|
| from fastapi import FastAPI, Request, Response
|
| app = FastAPI()
|
|
| @app.middleware("http")
| async def add_process_time_header(
| request: Request, call_next: Callable[[Request], Awaitable[Response]]
| ) -> Response:
| start_time = time.time()
| response = await call_next(request)
| process_time = time.time() - start_time
| response.headers["X-Process-Time"] = str(process_time)
| return response
| ```
|
| on_event(self, event_type: Annotated[str, Doc('\n The type of event. `startup` or `shutdown`.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add an event handler for the application.
|
| `on_event` is deprecated, use `lifespan` event handlers instead.
|
| Read more about it in the
| [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
|
| openapi(self) -> dict[str, typing.Any]
| Generate the OpenAPI schema of the application. This is called by FastAPI
| internally.
|
| The first time it is called it stores the result in the attribute
| `app.openapi_schema`, and next times it is called, it just returns that same
| result. To avoid the cost of generating the schema every time.
|
| If you need to modify the generated OpenAPI schema, you could modify it.
|
| Read more in the
| [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
|
| options(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210F50>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210F80>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210FB0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP OPTIONS operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.options("/items/")
| def get_item_options():
| return {"additions": ["Aji", "Guacamole"]}
| ```
|
| patch(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211070>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E542110A0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E542110D0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PATCH operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
|
| @app.patch("/items/")
| def update_item(item: Item):
| return {"message": "Item updated in place"}
| ```
|
| post(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E30>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E60>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E90>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP POST operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
|
| @app.post("/items/")
| def create_item(item: Item):
| return {"message": "Item created"}
| ```
|
| put(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210DA0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210DD0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E00>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PUT operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
|
| @app.put("/items/{item_id}")
| def replace_item(item_id: str, item: Item):
| return {"message": "Item replaced", "id": item_id}
| ```
|
| setup(self) -> None
|
| trace(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211100>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211130>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211160>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP TRACE operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.trace("/items/{item_id}")
| def trace_item(item_id: str):
| return None
| ```
|
| websocket(self, path: Annotated[str, Doc('\n WebSocket path.\n ')], name: Annotated[str | None, Doc('\n A name for the WebSocket. Only used internally.\n ')] = None, *, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n ')] = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Decorate a WebSocket function.
|
| Read more about it in the
| [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| **Example**
|
| ```python
| from fastapi import FastAPI, WebSocket
|
| app = FastAPI()
|
| @app.websocket("/ws")
| async def websocket_endpoint(websocket: WebSocket):
| await websocket.accept()
| while True:
| data = await websocket.receive_text()
| await websocket.send_text(f"Message text was: {data}")
| ```
|
| websocket_route(self, path: str, name: str | None = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.applications.Starlette:
|
| add_exception_handler(self, exc_class_or_status_code: 'int | type[Exception]', handler: 'ExceptionHandler') -> 'None'
|
| add_middleware(self, middleware_class: '_MiddlewareFactory[P]', *args: 'P.args', **kwargs: 'P.kwargs') -> 'None'
|
| add_route(self, path: 'str', route: 'Callable[[Request], Awaitable[Response] | Response]', methods: 'list[str] | None' = None, name: 'str | None' = None, include_in_schema: 'bool' = True) -> 'None'
|
| host(self, host: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| mount(self, path: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| url_path_for(self, name: 'str', /, **path_params: 'Any') -> 'URLPath'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from starlette.applications.Starlette:
|
| routes
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.applications.Starlette:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
fastapi.File
Python Library Documentation: function File in module fastapi.param_functions
File(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, media_type: Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'multipart/form-data', alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410EC30>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410ED20>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410EE40>]) -> Any
fastapi.Form
Python Library Documentation: function Form in module fastapi.param_functions
Form(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, media_type: Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'application/x-www-form-urlencoded', alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410E8D0>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410E9C0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410EAE0>]) -> Any
fastapi.HTTPException
Python Library Documentation: class HTTPException in module fastapi.exceptions
class HTTPException(starlette.exceptions.HTTPException)
| HTTPException(status_code: Annotated[int, Doc('\n HTTP status code to send to the client.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')], detail: Annotated[Any, Doc('\n Any data to be sent to the client in the `detail` key of the JSON\n response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')] = None, headers: Annotated[collections.abc.Mapping[str, str] | None, Doc('\n Any headers to send to the client in the response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)\n\n ')] = None) -> None
|
| An HTTP exception you can raise in your own code to show errors to the client.
|
| This is for client errors, invalid authentication, invalid data, etc. Not for server
| errors in your code.
|
| Read more about it in the
| [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI, HTTPException
|
| app = FastAPI()
|
| items = {"foo": "The Foo Wrestlers"}
|
|
| @app.get("/items/{item_id}")
| async def read_item(item_id: str):
| if item_id not in items:
| raise HTTPException(status_code=404, detail="Item not found")
| return {"item": items[item_id]}
| ```
|
| Method resolution order:
| HTTPException
| starlette.exceptions.HTTPException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, status_code: Annotated[int, Doc('\n HTTP status code to send to the client.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')], detail: Annotated[Any, Doc('\n Any data to be sent to the client in the `detail` key of the JSON\n response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')] = None, headers: Annotated[collections.abc.Mapping[str, str] | None, Doc('\n Any headers to send to the client in the response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)\n\n ')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.exceptions.HTTPException:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.exceptions.HTTPException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
fastapi.Header
Python Library Documentation: function Header in module fastapi.param_functions
Header(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, convert_underscores: Annotated[bool, Doc('\n Automatically convert underscores to hyphens in the parameter field name.\n\n Read more about it in the\n [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion)\n ')] = True, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410DD00>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410DDF0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410DF10>]) -> Any
fastapi.Path
Python Library Documentation: function Path in module fastapi.param_functions
Path(default: Annotated[Any, Doc("\n Default value if the parameter field is not set.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = Ellipsis, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n\n Read more about it in the\n [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata)\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E540EBD70>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410C560>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410CA10>]) -> Any
Declare a path parameter for a *path operation*.
Read more about it in the
[FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/).
```python
from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")],
):
return {"item_id": item_id}
```
fastapi.Query
Python Library Documentation: function Query in module fastapi.param_functions
Query(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value)\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters)\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410D1C0>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410D2B0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters)\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410D580>]) -> Any
fastapi.Request
Python Library Documentation: class Request in module starlette.requests
class Request(HTTPConnection)
| Request(scope: 'Scope', receive: 'Receive' = <function empty_receive at 0x0000024E540F1A80>, send: 'Send' = <function empty_send at 0x0000024E540F2660>)
|
| Method resolution order:
| Request
| HTTPConnection
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, scope: 'Scope', receive: 'Receive' = <function empty_receive at 0x0000024E540F1A80>, send: 'Send' = <function empty_send at 0x0000024E540F2660>)
| Initialize self. See help(type(self)) for accurate signature.
|
| async body(self) -> 'bytes'
|
| async close(self) -> 'None'
|
| form(self, *, max_files: 'int | float' = 1000, max_fields: 'int | float' = 1000, max_part_size: 'int' = 1048576) -> 'AwaitableOrContextManager[FormData]'
|
| async is_disconnected(self) -> 'bool'
|
| async json(self) -> 'Any'
|
| async send_push_promise(self, path: 'str') -> 'None'
|
| async stream(self) -> 'AsyncGenerator[bytes, None]'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| method
|
| receive
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'_form': 'FormData | None'}
|
| __orig_bases__ = (starlette.requests.HTTPConnection[~StateT],)
|
| __parameters__ = (~StateT,)
|
| ----------------------------------------------------------------------
| Methods inherited from HTTPConnection:
|
| __eq__(self, value, /) from builtins.object
| Return self==value.
|
| __getitem__(self, key: 'str') -> 'Any'
|
| __hash__(self, /) from builtins.object
| Return hash(self).
|
| __iter__(self) -> 'Iterator[str]'
|
| __len__(self) -> 'int'
|
| url_for(self, name: 'str', /, **path_params: 'Any') -> 'URL'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from HTTPConnection:
|
| app
|
| auth
|
| base_url
|
| client
|
| cookies
|
| headers
|
| path_params
|
| query_params
|
| session
|
| state
|
| url
|
| user
|
| ----------------------------------------------------------------------
| Data descriptors inherited from HTTPConnection:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Mapping:
|
| __contains__(self, key)
|
| get(self, key, default=None)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(self)
| D.items() -> a set-like object providing a view on D's items
|
| keys(self)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(self)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from collections.abc.Mapping:
|
| __reversed__ = None
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
fastapi.Response
Python Library Documentation: class Response in module starlette.responses class Response(builtins.object) | Response(content: 'Any' = None, status_code: 'int' = 200, headers: 'Mapping[str, str] | None' = None, media_type: 'str | None' = None, background: 'BackgroundTask | None' = None) -> 'None' | | Methods defined here: | | async __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None' | Call self as a function. | | __init__(self, content: 'Any' = None, status_code: 'int' = 200, headers: 'Mapping[str, str] | None' = None, media_type: 'str | None' = None, background: 'BackgroundTask | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | delete_cookie(self, key: 'str', path: 'str' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: "Literal['lax', 'strict', 'none'] | None" = 'lax') -> 'None' | | init_headers(self, headers: 'Mapping[str, str] | None' = None) -> 'None' | | render(self, content: 'Any') -> 'bytes | memoryview' | | set_cookie(self, key: 'str', value: 'str' = '', max_age: 'int | None' = None, expires: 'datetime | str | int | None' = None, path: 'str | None' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: "Literal['lax', 'strict', 'none'] | None" = 'lax', partitioned: 'bool' = False) -> 'None' | | ---------------------------------------------------------------------- | Readonly properties defined here: | | headers | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | charset = 'utf-8' | | media_type = None
fastapi.Security
Python Library Documentation: function Security in module fastapi.param_functions
Security(dependency: Annotated[collections.abc.Callable[..., Any] | None, Doc('\n A "dependable" callable (like a function).\n\n Don\'t call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n ')] = None, *, scopes: Annotated[collections.abc.Sequence[str] | None, Doc('\n OAuth2 scopes required for the *path operation* that uses this Security\n dependency.\n\n The term "scope" comes from the OAuth2 specification, it seems to be\n intentionally vague and interpretable. It normally refers to permissions,\n in cases to roles.\n\n These scopes are integrated with OpenAPI (and the API docs at `/docs`).\n So they are visible in the OpenAPI specification.\n\n Read more about it in the\n [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/)\n ')] = None, use_cache: Annotated[bool, Doc('\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n ')] = True) -> Any
Declare a FastAPI Security dependency.
The only difference with a regular dependency is that it can declare OAuth2
scopes that will be integrated with OpenAPI and the automatic UI docs (by default
at `/docs`).
It takes a single "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you.
Read more about it in the
[FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and
in the
[FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).
**Example**
```python
from typing import Annotated
from fastapi import Security, FastAPI
from .db import User
from .security import get_current_active_user
app = FastAPI()
@app.get("/users/me/items/")
async def read_own_items(
current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
return [{"item_id": "Foo", "owner": current_user.username}]
```
fastapi.UploadFile
Python Library Documentation: class UploadFile in module fastapi.datastructures
class UploadFile(starlette.datastructures.UploadFile)
| UploadFile(file: 'BinaryIO', *, size: 'int | None' = None, filename: 'str | None' = None, headers: 'Headers | None' = None) -> 'None'
|
| A file uploaded in a request.
|
| Define it as a *path operation function* (or dependency) parameter.
|
| If you are using a regular `def` function, you can use the `upload_file.file`
| attribute to access the raw standard Python file (blocking, not async), useful and
| needed for non-async code.
|
| Read more about it in the
| [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/).
|
| ## Example
|
| ```python
| from typing import Annotated
|
| from fastapi import FastAPI, File, UploadFile
|
| app = FastAPI()
|
|
| @app.post("/files/")
| async def create_file(file: Annotated[bytes, File()]):
| return {"file_size": len(file)}
|
|
| @app.post("/uploadfile/")
| async def create_upload_file(file: UploadFile):
| return {"filename": file.filename}
| ```
|
| Method resolution order:
| UploadFile
| starlette.datastructures.UploadFile
| builtins.object
|
| Methods defined here:
|
| async close(self) -> None
| Close the file.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| async read(self, size: Annotated[int, Doc('\n The number of bytes to read from the file.\n ')] = -1) -> bytes
| Read some bytes from the file.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| async seek(self, offset: Annotated[int, Doc('\n The position in bytes to seek to in the file.\n ')]) -> None
| Move to a position in the file.
|
| Any next read or write will be done from that position.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| async write(self, data: Annotated[bytes, Doc('\n The bytes to write to the file.\n ')]) -> None
| Write some bytes to the file.
|
| You normally wouldn't use this from a file you read in a request.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __get_pydantic_core_schema__(source: type[typing.Any], handler: collections.abc.Callable[[typing.Any], collections.abc.Mapping[str, typing.Any]]) -> collections.abc.Mapping[str, typing.Any]
|
| __get_pydantic_json_schema__(core_schema: collections.abc.Mapping[str, typing.Any], handler: pydantic.annotated_handlers.GetJsonSchemaHandler) -> dict[str, typing.Any]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content_type': typing.Annotated[str | None, Doc('T...
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.datastructures.UploadFile:
|
| __init__(self, file: 'BinaryIO', *, size: 'int | None' = None, filename: 'str | None' = None, headers: 'Headers | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from starlette.datastructures.UploadFile:
|
| content_type
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.datastructures.UploadFile:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
fastapi.WebSocket
Python Library Documentation: class WebSocket in module starlette.websockets
class WebSocket(starlette.requests.HTTPConnection)
| WebSocket(scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
|
| Method resolution order:
| WebSocket
| starlette.requests.HTTPConnection
| collections.abc.Mapping
| collections.abc.Collection
| collections.abc.Sized
| collections.abc.Iterable
| collections.abc.Container
| typing.Generic
| builtins.object
|
| Methods defined here:
|
| __init__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async accept(self, subprotocol: 'str | None' = None, headers: 'Iterable[tuple[bytes, bytes]] | None' = None) -> 'None'
|
| async close(self, code: 'int' = 1000, reason: 'str | None' = None) -> 'None'
|
| async iter_bytes(self) -> 'AsyncIterator[bytes]'
|
| async iter_json(self) -> 'AsyncIterator[Any]'
|
| async iter_text(self) -> 'AsyncIterator[str]'
|
| async receive(self) -> 'Message'
| Receive ASGI websocket messages, ensuring valid state transitions.
|
| async receive_bytes(self) -> 'bytes'
|
| async receive_json(self, mode: 'str' = 'text') -> 'Any'
|
| async receive_text(self) -> 'str'
|
| async send(self, message: 'Message') -> 'None'
| Send ASGI websocket messages, ensuring valid state transitions.
|
| async send_bytes(self, data: 'bytes') -> 'None'
|
| async send_denial_response(self, response: 'Response') -> 'None'
|
| async send_json(self, data: 'Any', mode: 'str' = 'text') -> 'None'
|
| async send_text(self, data: 'str') -> 'None'
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __orig_bases__ = (starlette.requests.HTTPConnection[~StateT],)
|
| __parameters__ = (~StateT,)
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.requests.HTTPConnection:
|
| __eq__(self, value, /) from builtins.object
| Return self==value.
|
| __getitem__(self, key: 'str') -> 'Any'
|
| __hash__(self, /) from builtins.object
| Return hash(self).
|
| __iter__(self) -> 'Iterator[str]'
|
| __len__(self) -> 'int'
|
| url_for(self, name: 'str', /, **path_params: 'Any') -> 'URL'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from starlette.requests.HTTPConnection:
|
| app
|
| auth
|
| base_url
|
| client
|
| cookies
|
| headers
|
| path_params
|
| query_params
|
| session
|
| state
|
| url
|
| user
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.requests.HTTPConnection:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from collections.abc.Mapping:
|
| __contains__(self, key)
|
| get(self, key, default=None)
| D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
|
| items(self)
| D.items() -> a set-like object providing a view on D's items
|
| keys(self)
| D.keys() -> a set-like object providing a view on D's keys
|
| values(self)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from collections.abc.Mapping:
|
| __reversed__ = None
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Collection:
|
| __subclasshook__(C)
| Abstract classes can override this to customize issubclass().
|
| This is invoked early on by abc.ABCMeta.__subclasscheck__().
| It should return True, False or NotImplemented. If it returns
| NotImplemented, the normal algorithm is used. Otherwise, it
| overrides the normal algorithm (and the outcome is cached).
|
| ----------------------------------------------------------------------
| Class methods inherited from collections.abc.Iterable:
|
| __class_getitem__ = GenericAlias(...)
| Represent a PEP 585 generic type
|
| E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,).
|
| ----------------------------------------------------------------------
| Class methods inherited from typing.Generic:
|
| __init_subclass__(...)
| Function to initialize subclasses.
fastapi.WebSocketDisconnect
Python Library Documentation: class WebSocketDisconnect in module starlette.websockets class WebSocketDisconnect(builtins.Exception) | WebSocketDisconnect(code: 'int' = 1000, reason: 'str | None' = None) -> 'None' | | Method resolution order: | WebSocketDisconnect | builtins.Exception | builtins.BaseException | builtins.object | | Methods defined here: | | __init__(self, code: 'int' = 1000, reason: 'str | None' = None) -> 'None' | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Static methods inherited from builtins.Exception: | | __new__(*args, **kwargs) class method of builtins.Exception | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
fastapi.WebSocketException
Python Library Documentation: class WebSocketException in module fastapi.exceptions
class WebSocketException(starlette.exceptions.WebSocketException)
| WebSocketException(code: Annotated[int, Doc('\n A closing code from the\n [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).\n ')], reason: Annotated[str | None, Doc('\n The reason to close the WebSocket connection.\n\n It is UTF-8-encoded data. The interpretation of the reason is up to the\n application, it is not specified by the WebSocket specification.\n\n It could contain text that could be human-readable or interpretable\n by the client code, etc.\n ')] = None) -> None
|
| A WebSocket exception you can raise in your own code to show errors to the client.
|
| This is for client errors, invalid authentication, invalid data, etc. Not for server
| errors in your code.
|
| Read more about it in the
| [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| ## Example
|
| ```python
| from typing import Annotated
|
| from fastapi import (
| Cookie,
| FastAPI,
| WebSocket,
| WebSocketException,
| status,
| )
|
| app = FastAPI()
|
| @app.websocket("/items/{item_id}/ws")
| async def websocket_endpoint(
| *,
| websocket: WebSocket,
| session: Annotated[str | None, Cookie()] = None,
| item_id: str,
| ):
| if session is None:
| raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
| await websocket.accept()
| while True:
| data = await websocket.receive_text()
| await websocket.send_text(f"Session cookie is: {session}")
| await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
| ```
|
| Method resolution order:
| WebSocketException
| starlette.exceptions.WebSocketException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, code: Annotated[int, Doc('\n A closing code from the\n [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).\n ')], reason: Annotated[str | None, Doc('\n The reason to close the WebSocket connection.\n\n It is UTF-8-encoded data. The interpretation of the reason is up to the\n application, it is not specified by the WebSocket specification.\n\n It could contain text that could be human-readable or interpretable\n by the client code, etc.\n ')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.exceptions.WebSocketException:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.exceptions.WebSocketException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
fastapi.applications
Python Library Documentation: module fastapi.applications in fastapi
NAME
fastapi.applications
CLASSES
starlette.applications.Starlette(builtins.object)
FastAPI
class FastAPI(starlette.applications.Starlette)
| FastAPI(*, debug: Annotated[bool, Doc('\n Boolean indicating if debug tracebacks should be returned on server\n errors.\n\n Read more in the\n [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette).\n ')] = False, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E542020F0>] = None, title: Annotated[str, Doc('\n The title of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(title="ChimichangApp")\n ```\n ')] = 'FastAPI', summary: Annotated[str | None, Doc('\n A short summary of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(summary="Deadpond\'s favorite app. Nuff said.")\n ```\n ')] = None, description: Annotated[str, Doc('\n A description of the API. Supports Markdown (using\n [CommonMark syntax](https://commonmark.org/)).\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n description="""\n ChimichangApp API helps you do awesome stuff. 🚀\n\n ## Items\n\n You can **read items**.\n\n ## Users\n\n You will be able to:\n\n * **Create users** (_not implemented_).\n * **Read users** (_not implemented_).\n\n """\n )\n ```\n ')] = '', version: Annotated[str, Doc('\n The version of the API.\n\n **Note** This is the version of your application, not the version of\n the OpenAPI specification nor the version of FastAPI being used.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(version="0.0.1")\n ```\n ')] = '0.1.0', openapi_url: Annotated[str | None, Doc('\n The URL where the OpenAPI schema will be served from.\n\n If you set it to `None`, no OpenAPI schema will be served publicly, and\n the default automatic endpoints `/docs` and `/redoc` will also be\n disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(openapi_url="/api/v1/openapi.json")\n ```\n ')] = '/openapi.json', openapi_tags: Annotated[list[dict[str, Any]] | None, Doc('\n A list of tags used by OpenAPI, these are the same `tags` you can set\n in the *path operations*, like:\n\n * `@app.get("/users/", tags=["users"])`\n * `@app.get("/items/", tags=["items"])`\n\n The order of the tags can be used to specify the order shown in\n tools like Swagger UI, used in the automatic path `/docs`.\n\n It\'s not required to specify all the tags used.\n\n The tags that are not declared MAY be organized randomly or based\n on the tools\' logic. Each tag name in the list MUST be unique.\n\n The value of each item is a `dict` containing:\n\n * `name`: The name of the tag.\n * `description`: A short description of the tag.\n [CommonMark syntax](https://commonmark.org/) MAY be used for rich\n text representation.\n * `externalDocs`: Additional external documentation for this tag. If\n provided, it would contain a `dict` with:\n * `description`: A short description of the target documentation.\n [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `url`: The URL for the target documentation. Value MUST be in\n the form of a URL.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n tags_metadata = [\n {\n "name": "users",\n "description": "Operations with users. The **login** logic is also here.",\n },\n {\n "name": "items",\n "description": "Manage items. So _fancy_ they have their own docs.",\n "externalDocs": {\n "description": "Items external docs",\n "url": "https://fastapi.tiangolo.com/",\n },\n },\n ]\n\n app = FastAPI(openapi_tags=tags_metadata)\n ```\n ')] = None, servers: Annotated[list[dict[str, str | Any]] | None, Doc('\n A `list` of `dict`s with connectivity information to a target server.\n\n You would use it, for example, if your application is served from\n different domains and you want to use the same Swagger UI in the\n browser to interact with each of them (instead of having multiple\n browser tabs open). Or if you want to leave fixed the possible URLs.\n\n If the servers `list` is not provided, or is an empty `list`, the\n `servers` property in the generated OpenAPI will be:\n\n * a `dict` with a `url` value of the application\'s mounting point\n (`root_path`) if it\'s different from `/`.\n * otherwise, the `servers` property will be omitted from the OpenAPI\n schema.\n\n Each item in the `list` is a `dict` containing:\n\n * `url`: A URL to the target host. This URL supports Server Variables\n and MAY be relative, to indicate that the host location is relative\n to the location where the OpenAPI document is being served. Variable\n substitutions will be made when a variable is named in `{`brackets`}`.\n * `description`: An optional string describing the host designated by\n the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `variables`: A `dict` between a variable name and its value. The value\n is used for substitution in the server\'s URL template.\n\n Read more in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n servers=[\n {"url": "https://stag.example.com", "description": "Staging environment"},\n {"url": "https://prod.example.com", "description": "Production environment"},\n ]\n )\n ```\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of global dependencies, they will be applied to each\n *path operation*, including in sub-routers.\n\n Read more about it in the\n [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import func_dep_1, func_dep_2\n\n app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])\n ```\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n app = FastAPI(default_response_class=ORJSONResponse)\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E51783EC0>, redirect_slashes: Annotated[bool, Doc('\n Whether to detect and redirect slashes in URLs when the client doesn\'t\n use the same format.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(redirect_slashes=True) # the default\n\n @app.get("/items/")\n async def read_items():\n return [{"item_id": "Foo"}]\n ```\n\n With this app, if a client goes to `/items` (without a trailing slash),\n they will be automatically redirected with an HTTP status code of 307\n to `/items/`.\n ')] = True, docs_url: Annotated[str | None, Doc('\n The path to the automatic interactive API documentation.\n It is handled in the browser by Swagger UI.\n\n The default URL is `/docs`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url=None)\n ```\n ')] = '/docs', redoc_url: Annotated[str | None, Doc('\n The path to the alternative automatic interactive API documentation\n provided by ReDoc.\n\n The default URL is `/redoc`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")\n ```\n ')] = '/redoc', swagger_ui_oauth2_redirect_url: Annotated[str | None, Doc('\n The OAuth2 redirect endpoint for the Swagger UI.\n\n By default it is `/docs/oauth2-redirect`.\n\n This is only used if you use OAuth2 (with the "Authorize" button)\n with Swagger UI.\n ')] = '/docs/oauth2-redirect', swagger_ui_init_oauth: Annotated[dict[str, Any] | None, Doc('\n OAuth2 configuration for the Swagger UI, by default shown at `/docs`.\n\n Read more about the available configuration options in the\n [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).\n ')] = None, middleware: Annotated[collections.abc.Sequence[starlette.middleware.Middleware] | None, Doc('\n List of middleware to be added when creating the application.\n\n In FastAPI you would normally do this with `app.add_middleware()`\n instead.\n\n Read more in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n ')] = None, exception_handlers: Annotated[dict[int | type[Exception], collections.abc.Callable[[starlette.requests.Request, Any], collections.abc.Coroutine[Any, Any, starlette.responses.Response]]] | None, Doc('\n A dictionary with handlers for exceptions.\n\n In FastAPI, you would normally use the decorator\n `@app.exception_handler()`.\n\n Read more in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n ')] = None, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, terms_of_service: Annotated[str | None, Doc('\n A URL to the Terms of Service for your API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(terms_of_service="http://example.com/terms/")\n ```\n ')] = None, contact: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the contact information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) The name of the contact person/organization.\n * `url`: (`str`) A URL pointing to the contact information. MUST be in\n the format of a URL.\n * `email`: (`str`) The email address of the contact person/organization.\n MUST be in the format of an email address.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n contact={\n "name": "Deadpoolio the Amazing",\n "url": "http://x-force.example.com/contact/",\n "email": "dp@x-force.example.com",\n }\n )\n ```\n ')] = None, license_info: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the license information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The\n license name used for the API.\n * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression\n for the API. The `identifier` field is mutually exclusive of the `url`\n field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.\n * `url`: (`str`) A URL to the license used for the API. This MUST be\n the format of a URL.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n license_info={\n "name": "Apache 2.0",\n "url": "https://www.apache.org/licenses/LICENSE-2.0.html",\n }\n )\n ```\n ')] = None, openapi_prefix: Annotated[str, Doc('\n A URL prefix for the OpenAPI URL.\n '), <typing_extensions.deprecated object at 0x0000024E54203620>] = '', root_path: Annotated[str, Doc('\n A path prefix handled by a proxy that is not seen by the application\n but is seen by external clients, which affects things like Swagger UI.\n\n Read more about it at the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path="/api/v1")\n ```\n ')] = '', root_path_in_servers: Annotated[bool, Doc('\n To disable automatically generating the URLs in the `servers` field\n in the autogenerated OpenAPI using the `root_path`.\n\n Read more about it in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path_in_servers=False)\n ```\n ')] = True, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, webhooks: Annotated[fastapi.routing.APIRouter | None, Doc("\n Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't\n depend on specific *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n ")] = None, deprecated: Annotated[bool | None, Doc("\n Mark all *path operations* as deprecated. You probably don't need it,\n but it's available.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).\n ")] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) all the *path operations* in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ")] = True, swagger_ui_parameters: Annotated[dict[str, Any] | None, Doc('\n Parameters to configure Swagger UI, the autogenerated interactive API\n documentation (by default at `/docs`).\n\n Read more about it in the\n [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54201FD0>, separate_input_output_schemas: Annotated[bool, Doc("\n Whether to generate separate OpenAPI schemas for request body and\n response body when the results would be more precise.\n\n This is particularly useful when automatically generating clients.\n\n For example, if you have a model like:\n\n ```python\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n tags: list[str] = []\n ```\n\n When `Item` is used for input, a request body, `tags` is not required,\n the client doesn't have to provide it.\n\n But when using `Item` for output, for a response body, `tags` is always\n available because it has a default value, even if it's just an empty\n list. So, the client should be able to always expect it.\n\n In this case, there would be two different schemas, one for input and\n another one for output.\n\n Read more about it in the\n [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)\n ")] = True, openapi_external_docs: Annotated[dict[str, Any] | None, Doc('\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n\n * `description`: A brief description of the external documentation.\n * `url`: The URL pointing to the external documentation. The value **MUST**\n be a valid URL format.\n\n **Example**:\n\n ```python\n from fastapi import FastAPI\n\n external_docs = {\n "description": "Detailed API Reference",\n "url": "https://example.com/api-docs",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n ```\n ')] = None, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = True, **extra: Annotated[Any, Doc('\n Extra keyword arguments to be stored in the app, not used by FastAPI\n anywhere.\n ')]) -> None
|
| `FastAPI` app class, the main entrypoint to use FastAPI.
|
| Read more in the
| [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
| ```
|
| Method resolution order:
| FastAPI
| starlette.applications.Starlette
| builtins.object
|
| Methods defined here:
|
| async __call__(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
| Call self as a function.
|
| __init__(self: ~AppType, *, debug: Annotated[bool, Doc('\n Boolean indicating if debug tracebacks should be returned on server\n errors.\n\n Read more in the\n [Starlette docs for Applications](https://starlette.dev/applications/#starlette.applications.Starlette).\n ')] = False, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E542020F0>] = None, title: Annotated[str, Doc('\n The title of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(title="ChimichangApp")\n ```\n ')] = 'FastAPI', summary: Annotated[str | None, Doc('\n A short summary of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(summary="Deadpond\'s favorite app. Nuff said.")\n ```\n ')] = None, description: Annotated[str, Doc('\n A description of the API. Supports Markdown (using\n [CommonMark syntax](https://commonmark.org/)).\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n description="""\n ChimichangApp API helps you do awesome stuff. 🚀\n\n ## Items\n\n You can **read items**.\n\n ## Users\n\n You will be able to:\n\n * **Create users** (_not implemented_).\n * **Read users** (_not implemented_).\n\n """\n )\n ```\n ')] = '', version: Annotated[str, Doc('\n The version of the API.\n\n **Note** This is the version of your application, not the version of\n the OpenAPI specification nor the version of FastAPI being used.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(version="0.0.1")\n ```\n ')] = '0.1.0', openapi_url: Annotated[str | None, Doc('\n The URL where the OpenAPI schema will be served from.\n\n If you set it to `None`, no OpenAPI schema will be served publicly, and\n the default automatic endpoints `/docs` and `/redoc` will also be\n disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(openapi_url="/api/v1/openapi.json")\n ```\n ')] = '/openapi.json', openapi_tags: Annotated[list[dict[str, Any]] | None, Doc('\n A list of tags used by OpenAPI, these are the same `tags` you can set\n in the *path operations*, like:\n\n * `@app.get("/users/", tags=["users"])`\n * `@app.get("/items/", tags=["items"])`\n\n The order of the tags can be used to specify the order shown in\n tools like Swagger UI, used in the automatic path `/docs`.\n\n It\'s not required to specify all the tags used.\n\n The tags that are not declared MAY be organized randomly or based\n on the tools\' logic. Each tag name in the list MUST be unique.\n\n The value of each item is a `dict` containing:\n\n * `name`: The name of the tag.\n * `description`: A short description of the tag.\n [CommonMark syntax](https://commonmark.org/) MAY be used for rich\n text representation.\n * `externalDocs`: Additional external documentation for this tag. If\n provided, it would contain a `dict` with:\n * `description`: A short description of the target documentation.\n [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `url`: The URL for the target documentation. Value MUST be in\n the form of a URL.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n tags_metadata = [\n {\n "name": "users",\n "description": "Operations with users. The **login** logic is also here.",\n },\n {\n "name": "items",\n "description": "Manage items. So _fancy_ they have their own docs.",\n "externalDocs": {\n "description": "Items external docs",\n "url": "https://fastapi.tiangolo.com/",\n },\n },\n ]\n\n app = FastAPI(openapi_tags=tags_metadata)\n ```\n ')] = None, servers: Annotated[list[dict[str, str | Any]] | None, Doc('\n A `list` of `dict`s with connectivity information to a target server.\n\n You would use it, for example, if your application is served from\n different domains and you want to use the same Swagger UI in the\n browser to interact with each of them (instead of having multiple\n browser tabs open). Or if you want to leave fixed the possible URLs.\n\n If the servers `list` is not provided, or is an empty `list`, the\n `servers` property in the generated OpenAPI will be:\n\n * a `dict` with a `url` value of the application\'s mounting point\n (`root_path`) if it\'s different from `/`.\n * otherwise, the `servers` property will be omitted from the OpenAPI\n schema.\n\n Each item in the `list` is a `dict` containing:\n\n * `url`: A URL to the target host. This URL supports Server Variables\n and MAY be relative, to indicate that the host location is relative\n to the location where the OpenAPI document is being served. Variable\n substitutions will be made when a variable is named in `{`brackets`}`.\n * `description`: An optional string describing the host designated by\n the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `variables`: A `dict` between a variable name and its value. The value\n is used for substitution in the server\'s URL template.\n\n Read more in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n servers=[\n {"url": "https://stag.example.com", "description": "Staging environment"},\n {"url": "https://prod.example.com", "description": "Production environment"},\n ]\n )\n ```\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of global dependencies, they will be applied to each\n *path operation*, including in sub-routers.\n\n Read more about it in the\n [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import func_dep_1, func_dep_2\n\n app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])\n ```\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n app = FastAPI(default_response_class=ORJSONResponse)\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E51783EC0>, redirect_slashes: Annotated[bool, Doc('\n Whether to detect and redirect slashes in URLs when the client doesn\'t\n use the same format.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(redirect_slashes=True) # the default\n\n @app.get("/items/")\n async def read_items():\n return [{"item_id": "Foo"}]\n ```\n\n With this app, if a client goes to `/items` (without a trailing slash),\n they will be automatically redirected with an HTTP status code of 307\n to `/items/`.\n ')] = True, docs_url: Annotated[str | None, Doc('\n The path to the automatic interactive API documentation.\n It is handled in the browser by Swagger UI.\n\n The default URL is `/docs`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url=None)\n ```\n ')] = '/docs', redoc_url: Annotated[str | None, Doc('\n The path to the alternative automatic interactive API documentation\n provided by ReDoc.\n\n The default URL is `/redoc`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")\n ```\n ')] = '/redoc', swagger_ui_oauth2_redirect_url: Annotated[str | None, Doc('\n The OAuth2 redirect endpoint for the Swagger UI.\n\n By default it is `/docs/oauth2-redirect`.\n\n This is only used if you use OAuth2 (with the "Authorize" button)\n with Swagger UI.\n ')] = '/docs/oauth2-redirect', swagger_ui_init_oauth: Annotated[dict[str, Any] | None, Doc('\n OAuth2 configuration for the Swagger UI, by default shown at `/docs`.\n\n Read more about the available configuration options in the\n [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).\n ')] = None, middleware: Annotated[collections.abc.Sequence[starlette.middleware.Middleware] | None, Doc('\n List of middleware to be added when creating the application.\n\n In FastAPI you would normally do this with `app.add_middleware()`\n instead.\n\n Read more in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n ')] = None, exception_handlers: Annotated[dict[int | type[Exception], collections.abc.Callable[[starlette.requests.Request, Any], collections.abc.Coroutine[Any, Any, starlette.responses.Response]]] | None, Doc('\n A dictionary with handlers for exceptions.\n\n In FastAPI, you would normally use the decorator\n `@app.exception_handler()`.\n\n Read more in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n ')] = None, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[~AppType], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, terms_of_service: Annotated[str | None, Doc('\n A URL to the Terms of Service for your API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(terms_of_service="http://example.com/terms/")\n ```\n ')] = None, contact: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the contact information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) The name of the contact person/organization.\n * `url`: (`str`) A URL pointing to the contact information. MUST be in\n the format of a URL.\n * `email`: (`str`) The email address of the contact person/organization.\n MUST be in the format of an email address.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n contact={\n "name": "Deadpoolio the Amazing",\n "url": "http://x-force.example.com/contact/",\n "email": "dp@x-force.example.com",\n }\n )\n ```\n ')] = None, license_info: Annotated[dict[str, str | Any] | None, Doc('\n A dictionary with the license information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The\n license name used for the API.\n * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression\n for the API. The `identifier` field is mutually exclusive of the `url`\n field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.\n * `url`: (`str`) A URL to the license used for the API. This MUST be\n the format of a URL.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n license_info={\n "name": "Apache 2.0",\n "url": "https://www.apache.org/licenses/LICENSE-2.0.html",\n }\n )\n ```\n ')] = None, openapi_prefix: Annotated[str, Doc('\n A URL prefix for the OpenAPI URL.\n '), <typing_extensions.deprecated object at 0x0000024E54203620>] = '', root_path: Annotated[str, Doc('\n A path prefix handled by a proxy that is not seen by the application\n but is seen by external clients, which affects things like Swagger UI.\n\n Read more about it at the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path="/api/v1")\n ```\n ')] = '', root_path_in_servers: Annotated[bool, Doc('\n To disable automatically generating the URLs in the `servers` field\n in the autogenerated OpenAPI using the `root_path`.\n\n Read more about it in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path_in_servers=False)\n ```\n ')] = True, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, webhooks: Annotated[fastapi.routing.APIRouter | None, Doc("\n Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't\n depend on specific *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n ")] = None, deprecated: Annotated[bool | None, Doc("\n Mark all *path operations* as deprecated. You probably don't need it,\n but it's available.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).\n ")] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) all the *path operations* in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ")] = True, swagger_ui_parameters: Annotated[dict[str, Any] | None, Doc('\n Parameters to configure Swagger UI, the autogenerated interactive API\n documentation (by default at `/docs`).\n\n Read more about it in the\n [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54201FD0>, separate_input_output_schemas: Annotated[bool, Doc("\n Whether to generate separate OpenAPI schemas for request body and\n response body when the results would be more precise.\n\n This is particularly useful when automatically generating clients.\n\n For example, if you have a model like:\n\n ```python\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n tags: list[str] = []\n ```\n\n When `Item` is used for input, a request body, `tags` is not required,\n the client doesn't have to provide it.\n\n But when using `Item` for output, for a response body, `tags` is always\n available because it has a default value, even if it's just an empty\n list. So, the client should be able to always expect it.\n\n In this case, there would be two different schemas, one for input and\n another one for output.\n\n Read more about it in the\n [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)\n ")] = True, openapi_external_docs: Annotated[dict[str, Any] | None, Doc('\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n\n * `description`: A brief description of the external documentation.\n * `url`: The URL pointing to the external documentation. The value **MUST**\n be a valid URL format.\n\n **Example**:\n\n ```python\n from fastapi import FastAPI\n\n external_docs = {\n "description": "Detailed API Reference",\n "url": "https://example.com/api-docs",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n ```\n ')] = None, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = True, **extra: Annotated[Any, Doc('\n Extra keyword arguments to be stored in the app, not used by FastAPI\n anywhere.\n ')]) -> None
| Initializes the application.
|
| Parameters:
| debug: Boolean indicating if debug tracebacks should be returned on errors.
| routes: A list of routes to serve incoming HTTP and WebSocket requests.
| middleware: A list of middleware to run for every request. A starlette
| application will always automatically include two middleware classes.
| `ServerErrorMiddleware` is added as the very outermost middleware, to handle
| any uncaught errors occurring anywhere in the entire stack.
| `ExceptionMiddleware` is added as the very innermost middleware, to deal
| with handled exception cases occurring in the routing or endpoints.
| exception_handlers: A mapping of either integer status codes,
| or exception class types onto callables which handle the exceptions.
| Exception handler callables should be of the form
| `handler(request, exc) -> response` and may be either standard functions, or
| async functions.
| lifespan: A lifespan context function, which can be used to perform
| startup and shutdown tasks. This is a newer style that replaces the
| `on_startup` and `on_shutdown` handlers. Use one or the other, not both.
|
| add_api_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54203F80>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54203FB0>, name: str | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54203FE0>) -> None
|
| add_api_websocket_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], name: str | None = None, *, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None) -> None
|
| api_route(self, path: str, *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E542103B0>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210410>, name: str | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210440>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| build_middleware_stack(self) -> collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]]
|
| delete(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210EC0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210EF0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210F20>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP DELETE operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.delete("/items/{item_id}")
| def delete_item(item_id: str):
| return {"message": "Item deleted"}
| ```
|
| exception_handler(self, exc_class_or_status_code: Annotated[int | type[Exception], Doc('\n The Exception class this would handle, or a status code.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add an exception handler to the app.
|
| Read more about it in the
| [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI, Request
| from fastapi.responses import JSONResponse
|
|
| class UnicornException(Exception):
| def __init__(self, name: str):
| self.name = name
|
|
| app = FastAPI()
|
|
| @app.exception_handler(UnicornException)
| async def unicorn_exception_handler(request: Request, exc: UnicornException):
| return JSONResponse(
| status_code=418,
| content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
| )
| ```
|
| frontend(self, path: Annotated[str, Doc('\n The URL path prefix where the frontend build should be served.\n ')], *, directory: Annotated[str | os.PathLike[str], Doc('\n The directory containing the static frontend build output.\n ')], fallback: Annotated[Optional[Literal['auto', 'index.html', '404.html']], Doc('\n The fallback file behavior for missing frontend paths.\n ')] = 'auto', check_dir: Annotated[Union[bool, Literal['auto']], Doc('\n Check that the frontend directory exists when the app is created. When\n set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is\n `"development"`, and check it otherwise. The `fastapi dev` command\n sets `FASTAPI_ENV` to `"development"` if it is not already set.\n ')] = 'auto') -> None
| Serve a static frontend build as low-priority routes.
|
| Use this for frontend tools that build static files into a directory,
| such as `dist`. **FastAPI** path operations are checked first, and
| the frontend files are checked only if no normal route matched.
|
| A typical project could look like this:
|
| ```text
| .
| ├── pyproject.toml
| ├── app
| │ ├── __init__.py
| │ └── main.py
| └── dist
| ├── index.html
| └── assets
| └── app.js
| ```
|
| Then in `app/main.py`:
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
| app.frontend("/", directory="dist")
| ```
|
| get(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210D10>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210D40>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210D70>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP GET operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.get("/items/")
| def read_items():
| return [{"name": "Empanada"}, {"name": "Arepa"}]
| ```
|
| head(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210FE0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211010>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211040>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP HEAD operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI, Response
|
| app = FastAPI()
|
| @app.head("/items/", status_code=204)
| def get_items_headers(response: Response):
| response.headers["X-Cat-Dog"] = "Alone in the world"
| ```
|
| include_router(self, router: Annotated[fastapi.routing.APIRouter, Doc('The `APIRouter` to include.')], *, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import get_token_header\n from .internal import admin\n\n app = FastAPI()\n\n app.include_router(\n admin.router,\n dependencies=[Depends(get_token_header)],\n )\n ```\n ')] = None, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all the *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n deprecated=True,\n )\n ```\n ')] = None, include_in_schema: Annotated[bool, Doc('\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n include_in_schema=False,\n )\n ```\n ')] = True, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n Default response class to be used for the *path operations* in this\n router.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n default_response_class=ORJSONResponse,\n )\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210800>, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210860>) -> None
| Include an `APIRouter` in the same app.
|
| Read more about it in the
| [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| from .users import users_router
|
| app = FastAPI()
|
| app.include_router(users_router)
| ```
|
| middleware(self, middleware_type: Annotated[str, Doc('\n The type of middleware. Currently only supports `http`.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a middleware to the application.
|
| Read more about it in the
| [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
|
| ## Example
|
| ```python
| import time
| from typing import Awaitable, Callable
|
| from fastapi import FastAPI, Request, Response
|
| app = FastAPI()
|
|
| @app.middleware("http")
| async def add_process_time_header(
| request: Request, call_next: Callable[[Request], Awaitable[Response]]
| ) -> Response:
| start_time = time.time()
| response = await call_next(request)
| process_time = time.time() - start_time
| response.headers["X-Process-Time"] = str(process_time)
| return response
| ```
|
| on_event(self, event_type: Annotated[str, Doc('\n The type of event. `startup` or `shutdown`.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add an event handler for the application.
|
| `on_event` is deprecated, use `lifespan` event handlers instead.
|
| Read more about it in the
| [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
|
| openapi(self) -> dict[str, typing.Any]
| Generate the OpenAPI schema of the application. This is called by FastAPI
| internally.
|
| The first time it is called it stores the result in the attribute
| `app.openapi_schema`, and next times it is called, it just returns that same
| result. To avoid the cost of generating the schema every time.
|
| If you need to modify the generated OpenAPI schema, you could modify it.
|
| Read more in the
| [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
|
| options(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210F50>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210F80>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210FB0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP OPTIONS operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.options("/items/")
| def get_item_options():
| return {"additions": ["Aji", "Guacamole"]}
| ```
|
| patch(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211070>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E542110A0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E542110D0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PATCH operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
|
| @app.patch("/items/")
| def update_item(item: Item):
| return {"message": "Item updated in place"}
| ```
|
| post(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E30>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E60>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E90>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP POST operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
|
| @app.post("/items/")
| def create_item(item: Item):
| return {"message": "Item created"}
| ```
|
| put(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210DA0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210DD0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54210E00>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PUT operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
|
| @app.put("/items/{item_id}")
| def replace_item(item_id: str, item: Item):
| return {"message": "Item replaced", "id": item_id}
| ```
|
| setup(self) -> None
|
| trace(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211100>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211130>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54211160>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP TRACE operation.
|
| ## Example
|
| ```python
| from fastapi import FastAPI
|
| app = FastAPI()
|
| @app.trace("/items/{item_id}")
| def trace_item(item_id: str):
| return None
| ```
|
| websocket(self, path: Annotated[str, Doc('\n WebSocket path.\n ')], name: Annotated[str | None, Doc('\n A name for the WebSocket. Only used internally.\n ')] = None, *, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n ')] = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Decorate a WebSocket function.
|
| Read more about it in the
| [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| **Example**
|
| ```python
| from fastapi import FastAPI, WebSocket
|
| app = FastAPI()
|
| @app.websocket("/ws")
| async def websocket_endpoint(websocket: WebSocket):
| await websocket.accept()
| while True:
| data = await websocket.receive_text()
| await websocket.send_text(f"Message text was: {data}")
| ```
|
| websocket_route(self, path: str, name: str | None = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.applications.Starlette:
|
| add_exception_handler(self, exc_class_or_status_code: 'int | type[Exception]', handler: 'ExceptionHandler') -> 'None'
|
| add_middleware(self, middleware_class: '_MiddlewareFactory[P]', *args: 'P.args', **kwargs: 'P.kwargs') -> 'None'
|
| add_route(self, path: 'str', route: 'Callable[[Request], Awaitable[Response] | Response]', methods: 'list[str] | None' = None, name: 'str | None' = None, include_in_schema: 'bool' = True) -> 'None'
|
| host(self, host: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| mount(self, path: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| url_path_for(self, name: 'str', /, **path_params: 'Any') -> 'URLPath'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from starlette.applications.Starlette:
|
| routes
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.applications.Starlette:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
ASGIApp = collections.abc.Callable[[collections.abc.Mutabl...aitable[N...
AppType = ~AppType
DecoratedCallable = ~DecoratedCallable
ExceptionHandler = collections.abc.Callable[['Request', Exception],......
IncEx = typing.Union[set[int], set[str], collections.abc...ng[str, typ...
Lifespan = collections.abc.Callable[[~AppType], contextlib....anager[c...
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
Receive = collections.abc.Callable[[], collections.abc.Awa...collectio...
Scope = collections.abc.MutableMapping[str, typing.Any]
Send = collections.abc.Callable[[collections.abc.Mutabl...r, typing.An...
logger = <Logger fastapi (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\applications.py
fastapi.background
Python Library Documentation: module fastapi.background in fastapi
NAME
fastapi.background
CLASSES
starlette.background.BackgroundTasks(starlette.background.BackgroundTask)
BackgroundTasks
class BackgroundTasks(starlette.background.BackgroundTasks)
| BackgroundTasks(tasks: 'Sequence[BackgroundTask] | None' = None)
|
| A collection of background tasks that will be called after a response has been
| sent to the client.
|
| Read more about it in the
| [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
|
| ## Example
|
| ```python
| from fastapi import BackgroundTasks, FastAPI
|
| app = FastAPI()
|
|
| def write_notification(email: str, message=""):
| with open("log.txt", mode="w") as email_file:
| content = f"notification for {email}: {message}"
| email_file.write(content)
|
|
| @app.post("/send-notification/{email}")
| async def send_notification(email: str, background_tasks: BackgroundTasks):
| background_tasks.add_task(write_notification, email, message="some notification")
| return {"message": "Notification sent in the background"}
| ```
|
| Method resolution order:
| BackgroundTasks
| starlette.background.BackgroundTasks
| starlette.background.BackgroundTask
| builtins.object
|
| Methods defined here:
|
| add_task(self, func: Annotated[collections.abc.Callable[~P, Any], Doc('\n The function to call after the response is sent.\n\n It can be a regular `def` function or an `async def` function.\n ')], *args: P.args, **kwargs: P.kwargs) -> None
| Add a function to be called in the background after the response is sent.
|
| Read more about it in the
| [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.background.BackgroundTasks:
|
| async __call__(self) -> 'None'
| Call self as a function.
|
| __init__(self, tasks: 'Sequence[BackgroundTask] | None' = None)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.background.BackgroundTask:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
DATA
P = ~P
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\background.py
fastapi.concurrency
Python Library Documentation: module fastapi.concurrency in fastapi
NAME
fastapi.concurrency
FUNCTIONS
contextmanager_in_threadpool(cm: contextlib.AbstractContextManager[~_T]) -> collections.abc.AsyncGenerator[~_T, None]
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\concurrency.py
fastapi.datastructures
Python Library Documentation: module fastapi.datastructures in fastapi
NAME
fastapi.datastructures
CLASSES
builtins.object
DefaultPlaceholder
starlette.datastructures.UploadFile(builtins.object)
UploadFile
class DefaultPlaceholder(builtins.object)
| DefaultPlaceholder(value: Any)
|
| You shouldn't use this class directly.
|
| It's used internally to recognize when a default value has been overwritten, even
| if the overridden default value was truthy.
|
| Methods defined here:
|
| __bool__(self) -> bool
|
| __eq__(self, o: object) -> bool
| Return self==value.
|
| __init__(self, value: Any)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class UploadFile(starlette.datastructures.UploadFile)
| UploadFile(file: 'BinaryIO', *, size: 'int | None' = None, filename: 'str | None' = None, headers: 'Headers | None' = None) -> 'None'
|
| A file uploaded in a request.
|
| Define it as a *path operation function* (or dependency) parameter.
|
| If you are using a regular `def` function, you can use the `upload_file.file`
| attribute to access the raw standard Python file (blocking, not async), useful and
| needed for non-async code.
|
| Read more about it in the
| [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/).
|
| ## Example
|
| ```python
| from typing import Annotated
|
| from fastapi import FastAPI, File, UploadFile
|
| app = FastAPI()
|
|
| @app.post("/files/")
| async def create_file(file: Annotated[bytes, File()]):
| return {"file_size": len(file)}
|
|
| @app.post("/uploadfile/")
| async def create_upload_file(file: UploadFile):
| return {"filename": file.filename}
| ```
|
| Method resolution order:
| UploadFile
| starlette.datastructures.UploadFile
| builtins.object
|
| Methods defined here:
|
| async close(self) -> None
| Close the file.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| async read(self, size: Annotated[int, Doc('\n The number of bytes to read from the file.\n ')] = -1) -> bytes
| Read some bytes from the file.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| async seek(self, offset: Annotated[int, Doc('\n The position in bytes to seek to in the file.\n ')]) -> None
| Move to a position in the file.
|
| Any next read or write will be done from that position.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| async write(self, data: Annotated[bytes, Doc('\n The bytes to write to the file.\n ')]) -> None
| Write some bytes to the file.
|
| You normally wouldn't use this from a file you read in a request.
|
| To be awaitable, compatible with async, this is run in threadpool.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __get_pydantic_core_schema__(source: type[typing.Any], handler: collections.abc.Callable[[typing.Any], collections.abc.Mapping[str, typing.Any]]) -> collections.abc.Mapping[str, typing.Any]
|
| __get_pydantic_json_schema__(core_schema: collections.abc.Mapping[str, typing.Any], handler: pydantic.annotated_handlers.GetJsonSchemaHandler) -> dict[str, typing.Any]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'content_type': typing.Annotated[str | None, Doc('T...
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.datastructures.UploadFile:
|
| __init__(self, file: 'BinaryIO', *, size: 'int | None' = None, filename: 'str | None' = None, headers: 'Headers | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| ----------------------------------------------------------------------
| Readonly properties inherited from starlette.datastructures.UploadFile:
|
| content_type
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.datastructures.UploadFile:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
Default(value: ~DefaultType) -> ~DefaultType
You shouldn't use this function directly.
It's used internally to recognize when a default value has been overwritten, even
if the overridden default value was truthy.
DATA
DefaultType = ~DefaultType
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\datastructures.py
fastapi.dependencies
Python Library Documentation: package fastapi.dependencies in fastapi
NAME
fastapi.dependencies
PACKAGE CONTENTS
models
utils
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\dependencies\__init__.py
fastapi.encoders
Python Library Documentation: module fastapi.encoders in fastapi
NAME
fastapi.encoders
CLASSES
builtins.object
PyExtraColor
class PyExtraColor(builtins.object)
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
FUNCTIONS
decimal_encoder(dec_value: decimal.Decimal) -> int | float
Encodes a Decimal as int if there's no exponent, otherwise float
This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
where an integer (but not int typed) is used. Encoding this as a float
results in failed round-tripping between encode and parse.
Our Id type is a prime example of this.
>>> decimal_encoder(Decimal("1.0"))
1.0
>>> decimal_encoder(Decimal("1"))
1
>>> decimal_encoder(Decimal("NaN"))
nan
generate_encoders_by_class_tuples(type_encoder_map: dict[typing.Any, collections.abc.Callable[[typing.Any], typing.Any]]) -> dict[collections.abc.Callable[[typing.Any], typing.Any], tuple[typing.Any, ...]]
isoformat(o: datetime.date | datetime.time) -> str
# Taken from Pydantic v1 as is
jsonable_encoder(obj: Annotated[Any, Doc('\n The input object to convert to JSON.\n ')], include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc("\n Pydantic's `include` parameter, passed to Pydantic models to set the\n fields to include.\n ")] = None, exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc("\n Pydantic's `exclude` parameter, passed to Pydantic models to set the\n fields to exclude.\n ")] = None, by_alias: Annotated[bool, Doc("\n Pydantic's `by_alias` parameter, passed to Pydantic models to define if\n the output should use the alias names (when provided) or the Python\n attribute names. In an API, if you set an alias, it's probably because you\n want to use it in the result, so you probably want to leave this set to\n `True`.\n ")] = True, exclude_unset: Annotated[bool, Doc("\n Pydantic's `exclude_unset` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that were not explicitly\n set (and that only had their default values).\n ")] = False, exclude_defaults: Annotated[bool, Doc("\n Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that had the same default\n value, even when they were explicitly set.\n ")] = False, exclude_none: Annotated[bool, Doc("\n Pydantic's `exclude_none` parameter, passed to Pydantic models to define\n if it should exclude from the output any fields that have a `None` value.\n ")] = False, custom_encoder: Annotated[dict[Any, collections.abc.Callable[[Any], Any]] | None, Doc("\n Pydantic's `custom_encoder` parameter, passed to Pydantic models to define\n a custom encoder.\n ")] = None, sqlalchemy_safe: Annotated[bool, Doc("\n Exclude from the output any fields that start with the name `_sa`.\n\n This is mainly a hack for compatibility with SQLAlchemy objects, they\n store internal SQLAlchemy-specific state in attributes named with `_sa`,\n and those objects can't (and shouldn't be) serialized to JSON.\n ")] = True) -> Any
Convert any object to something that can be encoded in JSON.
This is used internally by FastAPI to make sure anything you return can be
encoded as JSON before it is sent to the client.
You can also use it yourself, for example to convert objects before saving them
in a database that supports only JSON.
Read more about it in the
[FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).
DATA
ENCODERS_BY_TYPE = {<class 'bytes'>: <function <lambda>>, <class 'pyda...
IncEx = typing.Union[set[int], set[str], collections.abc...ng[str, typ...
__annotations__ = {'ENCODERS_BY_TYPE': dict[type[typing.Any], collecti...
encoders_by_class_tuples = defaultdict(<class 'tuple'>, {<function <la...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\encoders.py
fastapi.exception_handlers
Python Library Documentation: module fastapi.exception_handlers in fastapi
NAME
fastapi.exception_handlers
FUNCTIONS
async http_exception_handler(request: starlette.requests.Request, exc: starlette.exceptions.HTTPException) -> starlette.responses.Response
async request_validation_exception_handler(request: starlette.requests.Request, exc: fastapi.exceptions.RequestValidationError) -> starlette.responses.JSONResponse
async websocket_request_validation_exception_handler(websocket: starlette.websockets.WebSocket, exc: fastapi.exceptions.WebSocketRequestValidationError) -> None
DATA
WS_1008_POLICY_VIOLATION = 1008
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\exception_handlers.py
fastapi.exceptions
Python Library Documentation: module fastapi.exceptions in fastapi
NAME
fastapi.exceptions
CLASSES
builtins.Exception(builtins.BaseException)
ValidationException
RequestValidationError
ResponseValidationError
WebSocketRequestValidationError
builtins.RuntimeError(builtins.Exception)
FastAPIError
DependencyScopeError
PydanticV1NotSupportedError
builtins.UserWarning(builtins.Warning)
FastAPIDeprecationWarning
builtins.dict(builtins.object)
EndpointContext
pydantic.main.BaseModel(builtins.object)
Request
WebSocket
starlette.exceptions.HTTPException(builtins.Exception)
HTTPException
starlette.exceptions.WebSocketException(builtins.Exception)
WebSocketException
class DependencyScopeError(FastAPIError)
| A dependency declared that it depends on another dependency with an invalid
| (narrower) scope.
|
| Method resolution order:
| DependencyScopeError
| FastAPIError
| builtins.RuntimeError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors inherited from FastAPIError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.RuntimeError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.RuntimeError:
|
| __new__(*args, **kwargs) class method of builtins.RuntimeError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class EndpointContext(builtins.dict)
| Method resolution order:
| EndpointContext
| builtins.dict
| builtins.object
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'file': <class 'str'>, 'function': <class 'str'>, '...
|
| __optional_keys__ = frozenset({'file', 'function', 'line', 'path'})
|
| __orig_bases__ = (<function TypedDict>,)
|
| __required_keys__ = frozenset()
|
| __total__ = False
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.dict:
|
| __contains__(self, key, /)
| True if the dictionary has the specified key, else False.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __ior__(self, value, /)
| Return self|=value.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __or__(self, value, /)
| Return self|value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the dict keys.
|
| __ror__(self, value, /)
| Return value|self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| D.__sizeof__() -> size of D in memory, in bytes
|
| clear(...)
| D.clear() -> None. Remove all items from D.
|
| copy(...)
| D.copy() -> a shallow copy of D
|
| get(self, key, default=None, /)
| Return the value for key if key is in the dictionary, else default.
|
| items(...)
| D.items() -> a set-like object providing a view on D's items
|
| keys(...)
| D.keys() -> a set-like object providing a view on D's keys
|
| pop(...)
| D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
|
| If the key is not found, return the default if given; otherwise,
| raise a KeyError.
|
| popitem(self, /)
| Remove and return a (key, value) pair as a 2-tuple.
|
| Pairs are returned in LIFO (last-in, first-out) order.
| Raises KeyError if the dict is empty.
|
| setdefault(self, key, default=None, /)
| Insert key with a value of default if key is not in the dictionary.
|
| Return the value for key if key is in the dictionary, else default.
|
| update(...)
| D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
| If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
| If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
| In either case, this is followed by: for k in F: D[k] = F[k]
|
| values(...)
| D.values() -> an object providing a view on D's values
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.dict:
|
| __class_getitem__(...)
| See PEP 585
|
| fromkeys(iterable, value=None, /)
| Create a new dictionary with keys from iterable and values set to value.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.dict:
|
| __new__(*args, **kwargs) class method of builtins.dict
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from builtins.dict:
|
| __hash__ = None
class FastAPIDeprecationWarning(builtins.UserWarning)
| A custom deprecation warning as DeprecationWarning is ignored
| Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
|
| Method resolution order:
| FastAPIDeprecationWarning
| builtins.UserWarning
| builtins.Warning
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.UserWarning:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.UserWarning:
|
| __new__(*args, **kwargs) class method of builtins.UserWarning
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class FastAPIError(builtins.RuntimeError)
| A generic, FastAPI-specific error.
|
| Method resolution order:
| FastAPIError
| builtins.RuntimeError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.RuntimeError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.RuntimeError:
|
| __new__(*args, **kwargs) class method of builtins.RuntimeError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class HTTPException(starlette.exceptions.HTTPException)
| HTTPException(status_code: Annotated[int, Doc('\n HTTP status code to send to the client.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')], detail: Annotated[Any, Doc('\n Any data to be sent to the client in the `detail` key of the JSON\n response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')] = None, headers: Annotated[collections.abc.Mapping[str, str] | None, Doc('\n Any headers to send to the client in the response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)\n\n ')] = None) -> None
|
| An HTTP exception you can raise in your own code to show errors to the client.
|
| This is for client errors, invalid authentication, invalid data, etc. Not for server
| errors in your code.
|
| Read more about it in the
| [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
|
| ## Example
|
| ```python
| from fastapi import FastAPI, HTTPException
|
| app = FastAPI()
|
| items = {"foo": "The Foo Wrestlers"}
|
|
| @app.get("/items/{item_id}")
| async def read_item(item_id: str):
| if item_id not in items:
| raise HTTPException(status_code=404, detail="Item not found")
| return {"item": items[item_id]}
| ```
|
| Method resolution order:
| HTTPException
| starlette.exceptions.HTTPException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, status_code: Annotated[int, Doc('\n HTTP status code to send to the client.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')], detail: Annotated[Any, Doc('\n Any data to be sent to the client in the `detail` key of the JSON\n response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)\n ')] = None, headers: Annotated[collections.abc.Mapping[str, str] | None, Doc('\n Any headers to send to the client in the response.\n\n Read more about it in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)\n\n ')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.exceptions.HTTPException:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.exceptions.HTTPException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class PydanticV1NotSupportedError(FastAPIError)
| A pydantic.v1 model is used, which is no longer supported.
|
| Method resolution order:
| PydanticV1NotSupportedError
| FastAPIError
| builtins.RuntimeError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors inherited from FastAPIError:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.RuntimeError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.RuntimeError:
|
| __new__(*args, **kwargs) class method of builtins.RuntimeError
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
RequestErrorModel = class Request(pydantic.main.BaseModel)
| RequestErrorModel() -> None
|
| Method resolution order:
| Request
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'fastapi.exceptions.Request'...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {}
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="Request", validator=Mo...
|
| __signature__ = <Signature () -> None>
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {}
class RequestValidationError(ValidationException)
| RequestValidationError(errors: collections.abc.Sequence[typing.Any], *, body: Any = None, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
|
| Method resolution order:
| RequestValidationError
| ValidationException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, errors: collections.abc.Sequence[typing.Any], *, body: Any = None, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from ValidationException:
|
| __str__(self) -> str
| Return str(self).
|
| errors(self) -> collections.abc.Sequence[typing.Any]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ValidationException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ResponseValidationError(ValidationException)
| ResponseValidationError(errors: collections.abc.Sequence[typing.Any], *, body: Any = None, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
|
| Method resolution order:
| ResponseValidationError
| ValidationException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, errors: collections.abc.Sequence[typing.Any], *, body: Any = None, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from ValidationException:
|
| __str__(self) -> str
| Return str(self).
|
| errors(self) -> collections.abc.Sequence[typing.Any]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ValidationException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class ValidationException(builtins.Exception)
| ValidationException(errors: collections.abc.Sequence[typing.Any], *, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
|
| Method resolution order:
| ValidationException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, errors: collections.abc.Sequence[typing.Any], *, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __str__(self) -> str
| Return str(self).
|
| errors(self) -> collections.abc.Sequence[typing.Any]
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
WebSocketErrorModel = class WebSocket(pydantic.main.BaseModel)
| WebSocketErrorModel() -> None
|
| Method resolution order:
| WebSocket
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {}
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'cls': <class 'fastapi.exceptions.WebSocke...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {}
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="WebSocket", validator=...
|
| __signature__ = <Signature () -> None>
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {}
class WebSocketException(starlette.exceptions.WebSocketException)
| WebSocketException(code: Annotated[int, Doc('\n A closing code from the\n [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).\n ')], reason: Annotated[str | None, Doc('\n The reason to close the WebSocket connection.\n\n It is UTF-8-encoded data. The interpretation of the reason is up to the\n application, it is not specified by the WebSocket specification.\n\n It could contain text that could be human-readable or interpretable\n by the client code, etc.\n ')] = None) -> None
|
| A WebSocket exception you can raise in your own code to show errors to the client.
|
| This is for client errors, invalid authentication, invalid data, etc. Not for server
| errors in your code.
|
| Read more about it in the
| [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| ## Example
|
| ```python
| from typing import Annotated
|
| from fastapi import (
| Cookie,
| FastAPI,
| WebSocket,
| WebSocketException,
| status,
| )
|
| app = FastAPI()
|
| @app.websocket("/items/{item_id}/ws")
| async def websocket_endpoint(
| *,
| websocket: WebSocket,
| session: Annotated[str | None, Cookie()] = None,
| item_id: str,
| ):
| if session is None:
| raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
| await websocket.accept()
| while True:
| data = await websocket.receive_text()
| await websocket.send_text(f"Session cookie is: {session}")
| await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
| ```
|
| Method resolution order:
| WebSocketException
| starlette.exceptions.WebSocketException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, code: Annotated[int, Doc('\n A closing code from the\n [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).\n ')], reason: Annotated[str | None, Doc('\n The reason to close the WebSocket connection.\n\n It is UTF-8-encoded data. The interpretation of the reason is up to the\n application, it is not specified by the WebSocket specification.\n\n It could contain text that could be human-readable or interpretable\n by the client code, etc.\n ')] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.exceptions.WebSocketException:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __str__(self) -> 'str'
| Return str(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.exceptions.WebSocketException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
class WebSocketRequestValidationError(ValidationException)
| WebSocketRequestValidationError(errors: collections.abc.Sequence[typing.Any], *, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
|
| Method resolution order:
| WebSocketRequestValidationError
| ValidationException
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Methods defined here:
|
| __init__(self, errors: collections.abc.Sequence[typing.Any], *, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from ValidationException:
|
| __str__(self) -> str
| Return str(self).
|
| errors(self) -> collections.abc.Sequence[typing.Any]
|
| ----------------------------------------------------------------------
| Data descriptors inherited from ValidationException:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.Exception:
|
| __new__(*args, **kwargs) class method of builtins.Exception
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __setstate__(...)
|
| add_note(...)
| Exception.add_note(note) --
| add a note to the exception
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
DATA
__annotations__ = {'RequestErrorModel': type[pydantic.main.BaseModel],...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\exceptions.py
fastapi.logger
Python Library Documentation: module fastapi.logger in fastapi
NAME
fastapi.logger
DATA
logger = <Logger fastapi (WARNING)>
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\logger.py
fastapi.middleware
Python Library Documentation: package fastapi.middleware in fastapi
NAME
fastapi.middleware
PACKAGE CONTENTS
asyncexitstack
cors
gzip
httpsredirect
trustedhost
wsgi
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\middleware\__init__.py
fastapi.openapi
Python Library Documentation: package fastapi.openapi in fastapi
NAME
fastapi.openapi
PACKAGE CONTENTS
constants
docs
models
utils
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\openapi\__init__.py
fastapi.param_functions
Python Library Documentation: module fastapi.param_functions in fastapi
NAME
fastapi.param_functions
FUNCTIONS
Body(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, embed: Annotated[bool | None, Doc('\n When `embed` is `True`, the parameter will be expected in a JSON body as a\n key instead of being the JSON body itself.\n\n This happens automatically when more than one `Body` parameter is declared.\n\n Read more about it in the\n [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter).\n ')] = None, media_type: Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'application/json', alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410E570>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410E660>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410E780>]) -> Any
Cookie(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410E060>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410E150>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410E270>]) -> Any
Depends(dependency: Annotated[collections.abc.Callable[..., Any] | None, Doc('\n A "dependable" callable (like a function).\n\n Don\'t call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n ')] = None, *, use_cache: Annotated[bool, Doc('\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n ')] = True, scope: Annotated[Optional[Literal['function', 'request']], Doc('\n Mainly for dependencies with `yield`, define when the dependency function\n should start (the code before `yield`) and when it should end (the code\n after `yield`).\n\n * `"function"`: start the dependency before the *path operation function*\n that handles the request, end the dependency after the *path operation\n function* ends, but **before** the response is sent back to the client.\n So, the dependency function will be executed **around** the *path operation\n **function***.\n * `"request"`: start the dependency before the *path operation function*\n that handles the request (similar to when using `"function"`), but end\n **after** the response is sent back to the client. So, the dependency\n function will be executed **around** the **request** and response cycle.\n\n Read more about it in the\n [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)\n ')] = None) -> Any
Declare a FastAPI dependency.
It takes a single "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you.
Read more about it in the
[FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).
**Example**
```python
from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons
```
File(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, media_type: Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'multipart/form-data', alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410EC30>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410ED20>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410EE40>]) -> Any
Form(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, media_type: Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'application/x-www-form-urlencoded', alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410E8D0>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410E9C0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410EAE0>]) -> Any
Header(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, convert_underscores: Annotated[bool, Doc('\n Automatically convert underscores to hyphens in the parameter field name.\n\n Read more about it in the\n [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion)\n ')] = True, title: Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410DD00>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410DDF0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410DF10>]) -> Any
Path(default: Annotated[Any, Doc("\n Default value if the parameter field is not set.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = Ellipsis, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n\n Read more about it in the\n [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata)\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E540EBD70>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410C560>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410CA10>]) -> Any
Declare a path parameter for a *path operation*.
Read more about it in the
[FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/).
```python
from typing import Annotated
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: Annotated[int, Path(title="The ID of the item to get")],
):
return {"item_id": item_id}
```
Query(default: Annotated[Any, Doc('\n Default value if the parameter field is not set.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value)\n ')] = PydanticUndefined, *, default_factory: Annotated[collections.abc.Callable[[], Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, alias: Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters)\n ")] = None, alias_priority: Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: Annotated[str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: Annotated[str | None, Doc('\n Human-readable title.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)\n ')] = None, description: Annotated[str | None, Doc('\n Human-readable description.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata)\n ')] = None, gt: Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, ge: Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, lt: Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, le: Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n\n Read more about it in the\n [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal)\n ')] = None, min_length: Annotated[int | None, Doc('\n Minimum length for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)\n ')] = None, max_length: Annotated[int | None, Doc('\n Maximum length for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/)\n ')] = None, pattern: Annotated[str | None, Doc('\n RegEx pattern for strings.\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions\n ')] = None, regex: Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x0000024E5410D1C0>] = None, discriminator: Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: Annotated[list[Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E5410D2B0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: Annotated[dict[str, fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: Annotated[typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters)\n ')] = None, include_in_schema: Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi\n ")] = True, json_schema_extra: Annotated[dict[str, Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: Annotated[Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x0000024E5410D580>]) -> Any
Security(dependency: Annotated[collections.abc.Callable[..., Any] | None, Doc('\n A "dependable" callable (like a function).\n\n Don\'t call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n ')] = None, *, scopes: Annotated[collections.abc.Sequence[str] | None, Doc('\n OAuth2 scopes required for the *path operation* that uses this Security\n dependency.\n\n The term "scope" comes from the OAuth2 specification, it seems to be\n intentionally vague and interpretable. It normally refers to permissions,\n in cases to roles.\n\n These scopes are integrated with OpenAPI (and the API docs at `/docs`).\n So they are visible in the OpenAPI specification.\n\n Read more about it in the\n [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/)\n ')] = None, use_cache: Annotated[bool, Doc('\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n ')] = True) -> Any
Declare a FastAPI Security dependency.
The only difference with a regular dependency is that it can declare OAuth2
scopes that will be integrated with OpenAPI and the automatic UI docs (by default
at `/docs`).
It takes a single "dependable" callable (like a function).
Don't call it directly, FastAPI will call it for you.
Read more about it in the
[FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and
in the
[FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/).
**Example**
```python
from typing import Annotated
from fastapi import Security, FastAPI
from .db import User
from .security import get_current_active_user
app = FastAPI()
@app.get("/users/me/items/")
async def read_own_items(
current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])]
):
return [{"item_id": "Foo", "owner": current_user.username}]
```
DATA
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
Undefined = PydanticUndefined
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\param_functions.py
fastapi.params
Python Library Documentation: module fastapi.params in fastapi
NAME
fastapi.params
CLASSES
builtins.object
Depends
Security
enum.Enum(builtins.object)
ParamTypes
pydantic.fields.FieldInfo(pydantic._internal._repr.Representation)
Body
Form
File
Param
Cookie
Header
Path
Query
class Body(pydantic.fields.FieldInfo)
| Body(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, embed: bool | None = None, media_type: str = 'application/json', alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F95790>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F959D0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Body
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, embed: bool | None = None, media_type: str = 'application/json', alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F95790>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F959D0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Cookie(Param)
| Cookie(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F950A0>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F952E0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Cookie
| Param
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F950A0>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F952E0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| in_ = <ParamTypes.cookie: 'cookie'>
|
| ----------------------------------------------------------------------
| Methods inherited from Param:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Param:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Depends(builtins.object)
| Depends(dependency: collections.abc.Callable[..., typing.Any] | None = None, use_cache: bool = True, scope: Optional[Literal['function', 'request']] = None) -> None
|
| Depends(dependency: collections.abc.Callable[..., typing.Any] | None = None, use_cache: bool = True, scope: Optional[Literal['function', 'request']] = None)
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, dependency: collections.abc.Callable[..., typing.Any] | None = None, use_cache: bool = True, scope: Optional[Literal['function', 'request']] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'dependency': collections.abc.Callable[..., typing....
|
| __dataclass_fields__ = {'dependency': Field(name='dependency',type=col...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('dependency', 'use_cache', 'scope')
|
| dependency = None
|
| scope = None
|
| use_cache = True
class File(Form)
| File(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, media_type: str = 'multipart/form-data', alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F96510>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F96750>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| File
| Form
| Body
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, media_type: str = 'multipart/form-data', alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F96510>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F96750>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Body:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Body:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Form(Body)
| Form(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, media_type: str = 'application/x-www-form-urlencoded', alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F95E50>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F96090>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Form
| Body
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, media_type: str = 'application/x-www-form-urlencoded', alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F95E50>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F96090>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from Body:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Body:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Header(Param)
| Header(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, convert_underscores: bool = True, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F949E0>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F94C20>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Header
| Param
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, convert_underscores: bool = True, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F949E0>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F94C20>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| in_ = <ParamTypes.header: 'header'>
|
| ----------------------------------------------------------------------
| Methods inherited from Param:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Param:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Param(pydantic.fields.FieldInfo)
| Param(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53713560>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E537137A0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Param
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53713560>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E537137A0>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'in_': <enum 'ParamTypes'>}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class ParamTypes(enum.Enum)
| ParamTypes(*values)
|
| Method resolution order:
| ParamTypes
| enum.Enum
| builtins.object
|
| Data and other attributes defined here:
|
| cookie = <ParamTypes.cookie: 'cookie'>
|
| header = <ParamTypes.header: 'header'>
|
| path = <ParamTypes.path: 'path'>
|
| query = <ParamTypes.query: 'query'>
|
| ----------------------------------------------------------------------
| Data descriptors inherited from enum.Enum:
|
| name
| The name of the Enum member.
|
| value
| The value of the Enum member.
|
| ----------------------------------------------------------------------
| Static methods inherited from enum.EnumType:
|
| __contains__(value)
| Return True if `value` is in `cls`.
|
| `value` is in `cls` if:
| 1) `value` is a member of `cls`, or
| 2) `value` is the value of one of the `cls`'s members.
|
| __getitem__(name)
| Return the member matching `name`.
|
| __iter__()
| Return members in definition order.
|
| __len__()
| Return the number of members (no aliases)
|
| ----------------------------------------------------------------------
| Readonly properties inherited from enum.EnumType:
|
| __members__
| Returns a mapping of member name->value.
|
| This mapping lists all enum members, including aliases. Note that this
| is a read-only view of the internal mapping.
class Path(Param)
| Path(default: Any = Ellipsis, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53713C20>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53713E60>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Path
| Param
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = Ellipsis, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53713C20>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53713E60>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| in_ = <ParamTypes.path: 'path'>
|
| ----------------------------------------------------------------------
| Methods inherited from Param:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Param:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Query(Param)
| Query(default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F94320>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F94560>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
|
| Method resolution order:
| Query
| Param
| pydantic.fields.FieldInfo
| pydantic._internal._repr.Representation
| builtins.object
|
| Methods defined here:
|
| __init__(self, default: Any = PydanticUndefined, *, default_factory: collections.abc.Callable[[], typing.Any] | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, annotation: typing.Any | None = None, alias: str | None = None, alias_priority: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, validation_alias: str | pydantic.aliases.AliasPath | pydantic.aliases.AliasChoices | None = None, serialization_alias: str | None = None, title: str | None = None, description: str | None = None, gt: float | None = None, ge: float | None = None, lt: float | None = None, le: float | None = None, min_length: int | None = None, max_length: int | None = None, pattern: str | None = None, regex: Annotated[str | None, <typing_extensions.deprecated object at 0x0000024E53F94320>] = None, discriminator: str | None = None, strict: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, multiple_of: float | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, allow_inf_nan: bool | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, max_digits: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, decimal_places: int | None = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, examples: list[typing.Any] | None = None, example: Annotated[Any | None, <typing_extensions.deprecated object at 0x0000024E53F94560>] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E53713200>, openapi_examples: dict[str, fastapi.openapi.models.Example] | None = None, deprecated: typing_extensions.deprecated | str | bool | None = None, include_in_schema: bool = True, json_schema_extra: dict[str, typing.Any] | None = None, **extra: Any)
| This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function
| or one of the constructor classmethods.
|
| See the signature of `pydantic.fields.Field` for more details about the expected arguments.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| in_ = <ParamTypes.query: 'query'>
|
| ----------------------------------------------------------------------
| Methods inherited from Param:
|
| __repr__(self) -> str
| Return repr(self).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Param:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.fields.FieldInfo:
|
| __repr_args__(self) -> 'ReprArgs'
| Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
|
| Can either return:
| * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
| * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
|
| apply_typevars_map(self, typevars_map: 'Mapping[TypeVar, Any] | None', globalns: 'GlobalsNamespace | None' = None, localns: 'MappingNamespace | None' = None) -> 'None'
| Apply a `typevars_map` to the annotation.
|
| This method is used when analyzing parametrized generic types to replace typevars with their concrete types.
|
| This method applies the `typevars_map` to the annotation in place.
|
| Args:
| typevars_map: A dictionary mapping type variables to their concrete types.
| globalns: The globals namespace to use during type annotation evaluation.
| localns: The locals namespace to use during type annotation evaluation.
|
| See Also:
| pydantic._internal._generics.replace_types is used for replacing the typevars with
| their concrete types.
|
| asdict(self) -> '_FieldInfoAsDict'
| Return a dictionary representation of the `FieldInfo` instance.
|
| The returned value is a dictionary with three items:
|
| * `annotation`: The type annotation of the field.
| * `metadata`: The metadata list.
| * `attributes`: A mapping of the remaining `FieldInfo` attributes to their values (e.g. `alias`, `title`).
|
| get_default(self, *, call_default_factory: 'bool' = False, validated_data: 'dict[str, Any] | None' = None) -> 'Any'
| Get the default value.
|
| We expose an option for whether to call the default_factory (if present), as calling it may
| result in side effects that we want to avoid. However, there are times when it really should
| be called (namely, when instantiating a model via `model_construct`).
|
| Args:
| call_default_factory: Whether to call the default factory or not.
| validated_data: The already validated data to be passed to the default factory.
|
| Returns:
| The default value, calling the default factory if requested or `PydanticUndefined` if not set.
|
| is_required(self) -> 'bool'
| Check if the field is required (i.e., does not have a default value or factory).
|
| Returns:
| `True` if the field is required, `False` otherwise.
|
| rebuild_annotation(self) -> 'Any'
| Attempts to rebuild the original annotation for use in function signatures.
|
| If metadata is present, it adds it to the original annotation using
| `Annotated`. Otherwise, it returns the original annotation as-is.
|
| Note that because the metadata has been flattened, the original annotation
| may not be reconstructed exactly as originally provided, e.g. if the original
| type had unrecognized annotations, or was annotated with a call to `pydantic.Field`.
|
| Returns:
| The rebuilt annotation.
|
| ----------------------------------------------------------------------
| Static methods inherited from pydantic.fields.FieldInfo:
|
| from_annotated_attribute(annotation: 'type[Any]', default: 'Any', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Create `FieldInfo` from an annotation with a default value.
|
| This is used in cases like the following:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = 4 # <-- like this
| bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this
| spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this
| ```
|
| Args:
| annotation: The type annotation of the field.
| default: The default value of the field.
|
| Returns:
| A field object with the passed values.
|
| from_annotation(annotation: 'type[Any]', *, _source: 'AnnotationSource' = <AnnotationSource.ANY: 7>) -> 'FieldInfo'
| Creates a `FieldInfo` instance from a bare annotation.
|
| This function is used internally to create a `FieldInfo` from a bare annotation like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int # <-- like this
| ```
|
| We also account for the case where the annotation can be an instance of `Annotated` and where
| one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.:
|
| ```python
| from typing import Annotated
|
| import annotated_types
|
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: Annotated[int, annotated_types.Gt(42)]
| bar: Annotated[int, pydantic.Field(gt=42)]
| ```
|
| Args:
| annotation: An annotation object.
|
| Returns:
| An instance of the field metadata.
|
| from_field(default: 'Any' = PydanticUndefined, **kwargs: 'Unpack[_FromFieldInfoInputs]') -> 'FieldInfo'
| Create a new `FieldInfo` object with the `Field` function.
|
| Args:
| default: The default value for the field. Defaults to Undefined.
| **kwargs: Additional arguments dictionary.
|
| Raises:
| TypeError: If 'annotation' is passed as a keyword argument.
|
| Returns:
| A new FieldInfo object with the given parameters.
|
| Example:
| This is how you can create a field with default value like this:
|
| ```python
| import pydantic
|
| class MyModel(pydantic.BaseModel):
| foo: int = pydantic.Field(4)
| ```
|
| merge_field_infos(*field_infos: 'FieldInfo', **overrides: 'Any') -> 'FieldInfo'
| Merge `FieldInfo` instances keeping only explicitly set attributes.
|
| Later `FieldInfo` instances override earlier ones.
|
| Returns:
| FieldInfo: A merged FieldInfo instance.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.fields.FieldInfo:
|
| default_factory_takes_validated_data
| Whether the provided default factory callable has a validated data parameter.
|
| Returns `None` if no default factory is set.
|
| deprecation_message
| The deprecation message to be emitted, or `None` if not set.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.fields.FieldInfo:
|
| alias
|
| alias_priority
|
| annotation
|
| default
|
| default_factory
|
| deprecated
|
| description
|
| discriminator
|
| examples
|
| exclude
|
| exclude_if
|
| field_title_generator
|
| frozen
|
| init
|
| init_var
|
| json_schema_extra
|
| kw_only
|
| metadata
|
| repr
|
| serialization_alias
|
| title
|
| validate_default
|
| validation_alias
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.fields.FieldInfo:
|
| __final__ = True
|
| metadata_lookup = {'allow_inf_nan': None, 'coerce_numbers_to_str': Non...
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic._internal._repr.Representation:
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]'
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __repr_name__(self) -> 'str'
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str'
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str'
|
| __rich_repr__(self) -> 'RichReprResult'
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __str__(self) -> 'str'
| Return str(self).
class Security(Depends)
| Security(dependency: collections.abc.Callable[..., typing.Any] | None = None, use_cache: bool = True, scope: Optional[Literal['function', 'request']] = None, scopes: collections.abc.Sequence[str] | None = None) -> None
|
| Security(dependency: collections.abc.Callable[..., typing.Any] | None = None, use_cache: bool = True, scope: Optional[Literal['function', 'request']] = None, scopes: collections.abc.Sequence[str] | None = None)
|
| Method resolution order:
| Security
| Depends
| builtins.object
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, dependency: collections.abc.Callable[..., typing.Any] | None = None, use_cache: bool = True, scope: Optional[Literal['function', 'request']] = None, scopes: collections.abc.Sequence[str] | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'scopes': collections.abc.Sequence[str] | None}
|
| __dataclass_fields__ = {'dependency': Field(name='dependency',type=col...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('dependency', 'use_cache', 'scope', 'scopes')
|
| scopes = None
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Depends:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Depends:
|
| dependency = None
|
| scope = None
|
| use_cache = True
DATA
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
Undefined = PydanticUndefined
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\params.py
fastapi.requests
Python Library Documentation: module fastapi.requests in fastapi
NAME
fastapi.requests
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\requests.py
fastapi.responses
Error rendering doc: unsupported operand type(s) for +: 'NoneType' and 'str'
fastapi.routing
Python Library Documentation: module fastapi.routing in fastapi
NAME
fastapi.routing
CLASSES
builtins.object
RouteContext
starlette.routing.Route(starlette.routing.BaseRoute)
APIRoute
starlette.routing.Router(builtins.object)
APIRouter
starlette.routing.WebSocketRoute(starlette.routing.BaseRoute)
APIWebSocketRoute
class APIRoute(starlette.routing.Route)
| APIRoute(path: str, endpoint: collections.abc.Callable[..., typing.Any], *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0800>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, name: str | None = None, methods: set[str] | list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0830>, dependency_overrides_provider: typing.Any | None = None, callbacks: list[starlette.routing.BaseRoute] | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[['APIRoute'], str] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0860>, strict_content_type: bool | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0890>) -> None
|
| Method resolution order:
| APIRoute
| starlette.routing.Route
| starlette.routing.BaseRoute
| builtins.object
|
| Methods defined here:
|
| __init__(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0800>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, name: str | None = None, methods: set[str] | list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0830>, dependency_overrides_provider: typing.Any | None = None, callbacks: list[starlette.routing.BaseRoute] | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[['APIRoute'], str] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0860>, strict_content_type: bool | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B0890>) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| get_route_handler(self) -> collections.abc.Callable[[starlette.requests.Request], collections.abc.Coroutine[typing.Any, typing.Any, starlette.responses.Response]]
|
| async handle(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
|
| matches(self, scope: collections.abc.MutableMapping[str, typing.Any]) -> tuple[starlette.routing.Match, collections.abc.MutableMapping[str, typing.Any]]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_embed_body_fields': <class 'bool'>, 'body_field':...
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.routing.Route:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| url_path_for(self, name: 'str', /, **path_params: 'Any') -> 'URLPath'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from starlette.routing.Route:
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.routing.BaseRoute:
|
| async __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| A route may be used in isolation as a stand-alone ASGI app.
| This is a somewhat contrived case, as they'll almost always be used
| within a Router, but could be useful for some tooling and minimal apps.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.routing.BaseRoute:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class APIRouter(starlette.routing.Router)
| APIRouter(*, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2BD0>, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E541B35F0>] = None, redirect_slashes: Annotated[bool, Doc("\n Whether to detect and redirect slashes in URLs when the client doesn't\n use the same format.\n ")] = True, default: Annotated[collections.abc.Callable[[collections.abc.MutableMapping[str, Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]] | None, Doc('\n Default function handler for this router. Used to handle\n 404 Not Found errors.\n ')] = None, dependency_overrides_provider: Annotated[Any | None, Doc("\n Only used internally by FastAPI to handle dependency overrides.\n\n You shouldn't need to use it. It normally points to the `FastAPI` app\n object.\n ")] = None, route_class: Annotated[type[fastapi.routing.APIRoute], Doc('\n Custom route (*path operation*) class to be used by this router.\n\n Read more about it in the\n [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).\n ')] = <class 'fastapi.routing.APIRoute'>, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, include_in_schema: Annotated[bool, Doc('\n To include (or not) all the *path operations* in this router in the\n generated OpenAPI.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C30>, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C60>) -> None
|
| `APIRouter` class, used to group *path operations*, for example to structure
| an app in multiple files. It would then be included in the `FastAPI` app, or
| in another `APIRouter` (ultimately included in the app).
|
| Read more about it in the
| [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
|
| @router.get("/users/", tags=["users"])
| async def read_users():
| return [{"username": "Rick"}, {"username": "Morty"}]
|
|
| app.include_router(router)
| ```
|
| Method resolution order:
| APIRouter
| starlette.routing.Router
| builtins.object
|
| Methods defined here:
|
| __init__(self, *, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2BD0>, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, routes: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x0000024E541B35F0>] = None, redirect_slashes: Annotated[bool, Doc("\n Whether to detect and redirect slashes in URLs when the client doesn't\n use the same format.\n ")] = True, default: Annotated[collections.abc.Callable[[collections.abc.MutableMapping[str, Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]] | None, Doc('\n Default function handler for this router. Used to handle\n 404 Not Found errors.\n ')] = None, dependency_overrides_provider: Annotated[Any | None, Doc("\n Only used internally by FastAPI to handle dependency overrides.\n\n You shouldn't need to use it. It normally points to the `FastAPI` app\n object.\n ")] = None, route_class: Annotated[type[fastapi.routing.APIRoute], Doc('\n Custom route (*path operation*) class to be used by this router.\n\n Read more about it in the\n [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router).\n ')] = <class 'fastapi.routing.APIRoute'>, on_startup: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: Annotated[collections.abc.Sequence[collections.abc.Callable[[], Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: Annotated[collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[None]] | collections.abc.Callable[[Any], contextlib.AbstractAsyncContextManager[collections.abc.Mapping[str, Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, include_in_schema: Annotated[bool, Doc('\n To include (or not) all the *path operations* in this router in the\n generated OpenAPI.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C30>, strict_content_type: Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541B2C60>) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| add_api_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D49E0>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: set[str] | list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4A10>, name: str | None = None, route_class_override: type[fastapi.routing.APIRoute] | None = None, callbacks: list[starlette.routing.BaseRoute] | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4A40>, strict_content_type: bool | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4A70>) -> None
|
| add_api_websocket_route(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], name: str | None = None, *, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None) -> None
|
| add_event_handler(self, event_type: str, func: collections.abc.Callable[[], typing.Any]) -> None
| Add an event handler function for startup or shutdown.
|
| This method is kept for backward compatibility after Starlette removed
| support for on_startup/on_shutdown handlers.
|
| Ref: https://github.com/Kludex/starlette/pull/3117
|
| add_route(self, path: str, endpoint: collections.abc.Callable[[starlette.requests.Request], collections.abc.Awaitable[starlette.responses.Response] | starlette.responses.Response], methods: collections.abc.Collection[str] | None = None, name: str | None = None, include_in_schema: bool = True) -> None
|
| add_websocket_route(self, path: str, endpoint: collections.abc.Callable[[starlette.websockets.WebSocket], collections.abc.Awaitable[None]], name: str | None = None) -> None
|
| api_route(self, path: str, *, response_model: Any = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4F50>, status_code: int | None = None, tags: list[str | enum.Enum] | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4F80>, name: str | None = None, callbacks: list[starlette.routing.BaseRoute] | None = None, openapi_extra: dict[str, typing.Any] | None = None, generate_unique_id_function: collections.abc.Callable[[fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D4FB0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| async app(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
|
| delete(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F30>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F60>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F90>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP DELETE operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
| @router.delete("/items/{item_id}")
| def delete_item(item_id: str):
| return {"message": "Item deleted"}
|
| app.include_router(router)
| ```
|
| frontend(self, path: Annotated[str, Doc('\n The URL path prefix where the frontend build should be served.\n ')], *, directory: Annotated[str | os.PathLike[str], Doc('\n The directory containing the static frontend build output.\n ')], fallback: Annotated[Optional[Literal['auto', 'index.html', '404.html']], Doc('\n The fallback file behavior for missing frontend paths.\n ')] = 'auto', check_dir: Annotated[Union[bool, Literal['auto']], Doc('\n Check that the frontend directory exists when the app is created. When\n set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is\n `"development"`, and check it otherwise. The `fastapi dev` command\n sets `FASTAPI_ENV` to `"development"` if it is not already set.\n ')] = 'auto') -> None
| Serve a static frontend build as low-priority routes.
|
| Use this for frontend tools that build static files into a directory,
| such as `dist`. **FastAPI** path operations are checked first, and
| the frontend files are checked only if no normal route matched.
|
| A typical project could look like this:
|
| ```text
| .
| ├── pyproject.toml
| ├── app
| │ ├── __init__.py
| │ └── main.py
| └── dist
| ├── index.html
| └── assets
| └── app.js
| ```
|
| Then in `app/main.py`:
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
| router.frontend("/", directory="dist")
| app.include_router(router)
| ```
|
| get(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D59A0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5A00>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5A30>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP GET operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
| @router.get("/items/")
| def read_items():
| return [{"name": "Empanada"}, {"name": "Arepa"}]
|
| app.include_router(router)
| ```
|
| async handle(self, scope: collections.abc.MutableMapping[str, typing.Any], receive: collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], send: collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]) -> None
|
| head(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7050>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7080>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D70B0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP HEAD operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.head("/items/", status_code=204)
| def get_items_headers(response: Response):
| response.headers["X-Cat-Dog"] = "Alone in the world"
|
| app.include_router(router)
| ```
|
| include_router(self, router: Annotated[ForwardRef('APIRouter'), Doc('The `APIRouter` to include.')], *, prefix: Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [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).\n ')] = None, default_response_class: Annotated[type[starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5730>, responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark all *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, include_in_schema: Annotated[bool, Doc('\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ')] = True, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D5760>) -> None
| Include another `APIRouter` in the same current `APIRouter`.
|
| Read more about it in the
| [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| internal_router = APIRouter()
| users_router = APIRouter()
|
| @users_router.get("/users/")
| def read_users():
| return [{"name": "Rick"}, {"name": "Morty"}]
|
| internal_router.include_router(users_router)
| app.include_router(internal_router)
| ```
|
| matches(self, scope: collections.abc.MutableMapping[str, typing.Any]) -> tuple[starlette.routing.Match, collections.abc.MutableMapping[str, typing.Any]]
|
| on_event(self, event_type: Annotated[str, Doc('\n The type of event. `startup` or `shutdown`.\n ')]) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add an event handler for the router.
|
| `on_event` is deprecated, use `lifespan` event handlers instead.
|
| Read more about it in the
| [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
|
| options(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6FC0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6FF0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7020>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP OPTIONS operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
|
| app = FastAPI()
| router = APIRouter()
|
| @router.options("/items/")
| def get_item_options():
| return {"additions": ["Aji", "Guacamole"]}
|
| app.include_router(router)
| ```
|
| patch(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D70E0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7110>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7140>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PATCH operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.patch("/items/")
| def update_item(item: Item):
| return {"message": "Item updated in place"}
|
| app.include_router(router)
| ```
|
| post(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6EA0>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6ED0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6F00>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP POST operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.post("/items/")
| def create_item(item: Item):
| return {"message": "Item created"}
|
| app.include_router(router)
| ```
|
| put(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6E10>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6E40>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D6E70>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP PUT operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.put("/items/{item_id}")
| def replace_item(item_id: str, item: Item):
| return {"message": "Item replaced", "id": item_id}
|
| app.include_router(router)
| ```
|
| route(self, path: str, methods: collections.abc.Collection[str] | None = None, name: str | None = None, include_in_schema: bool = True) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| trace(self, path: Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: Annotated[Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D7170>, status_code: Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: Annotated[list[str | enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: Annotated[dict[int | str, dict[str, Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: Annotated[Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType], Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: Annotated[type[starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D71A0>, name: Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: Annotated[list[starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: Annotated[dict[str, Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: Annotated[collections.abc.Callable[[fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E541D71D0>) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Add a *path operation* using an HTTP TRACE operation.
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI
| from pydantic import BaseModel
|
| class Item(BaseModel):
| name: str
| description: str | None = None
|
| app = FastAPI()
| router = APIRouter()
|
| @router.trace("/items/{item_id}")
| def trace_item(item_id: str):
| return None
|
| app.include_router(router)
| ```
|
| websocket(self, path: Annotated[str, Doc('\n WebSocket path.\n ')], name: Annotated[str | None, Doc('\n A name for the WebSocket. Only used internally.\n ')] = None, *, dependencies: Annotated[collections.abc.Sequence[fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n ')] = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
| Decorate a WebSocket function.
|
| Read more about it in the
| [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
|
| **Example**
|
| ## Example
|
| ```python
| from fastapi import APIRouter, FastAPI, WebSocket
|
| app = FastAPI()
| router = APIRouter()
|
| @router.websocket("/ws")
| async def websocket_endpoint(websocket: WebSocket):
| await websocket.accept()
| while True:
| data = await websocket.receive_text()
| await websocket.send_text(f"Message text was: {data}")
|
| app.include_router(router)
| ```
|
| websocket_route(self, path: str, name: str | None = None) -> collections.abc.Callable[[~DecoratedCallable], ~DecoratedCallable]
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.routing.Router:
|
| async __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| The main entry point to the Router class.
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| host(self, host: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| async lifespan(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| Handle ASGI lifespan messages, which allows us to manage application
| startup and shutdown events.
|
| mount(self, path: 'str', app: 'ASGIApp', name: 'str | None' = None) -> 'None'
|
| async not_found(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
|
| url_path_for(self, name: 'str', /, **path_params: 'Any') -> 'URLPath'
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.routing.Router:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from starlette.routing.Router:
|
| __hash__ = None
class APIWebSocketRoute(starlette.routing.WebSocketRoute)
| APIWebSocketRoute(path: str, endpoint: collections.abc.Callable[..., typing.Any], *, name: str | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, dependency_overrides_provider: typing.Any | None = None) -> None
|
| Method resolution order:
| APIWebSocketRoute
| starlette.routing.WebSocketRoute
| starlette.routing.BaseRoute
| builtins.object
|
| Methods defined here:
|
| __init__(self, path: str, endpoint: collections.abc.Callable[..., typing.Any], *, name: str | None = None, dependencies: collections.abc.Sequence[fastapi.params.Depends] | None = None, dependency_overrides_provider: typing.Any | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| matches(self, scope: collections.abc.MutableMapping[str, typing.Any]) -> tuple[starlette.routing.Match, collections.abc.MutableMapping[str, typing.Any]]
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.routing.WebSocketRoute:
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| async handle(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
|
| url_path_for(self, name: 'str', /, **path_params: 'Any') -> 'URLPath'
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from starlette.routing.WebSocketRoute:
|
| __hash__ = None
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.routing.BaseRoute:
|
| async __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| A route may be used in isolation as a stand-alone ASGI app.
| This is a somewhat contrived case, as they'll almost always be used
| within a Router, but could be useful for some tooling and minimal apps.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.routing.BaseRoute:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class RouteContext(builtins.object)
| RouteContext(route: starlette.routing.BaseRoute, _route_context: fastapi.routing._EffectiveRouteContext | None = None) -> None
|
| RouteContext(route: starlette.routing.BaseRoute, _route_context: fastapi.routing._EffectiveRouteContext | None = None)
|
| Methods defined here:
|
| __delattr__(self, name)
| Implement delattr(self, name).
|
| __eq__(self, other)
| Return self==value.
|
| __getattr__(self, name: str) -> Any
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, route: starlette.routing.BaseRoute, _route_context: fastapi.routing._EffectiveRouteContext | None = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__(self)
| Return repr(self).
|
| __setattr__(self, name, value)
| Implement setattr(self, name, value).
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| endpoint
|
| methods
|
| name
|
| original_route
|
| path
|
| path_format
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_route_context': fastapi.routing._EffectiveRouteCo...
|
| __dataclass_fields__ = {'_route_context': Field(name='_route_context',...
|
| __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
|
| __match_args__ = ('route', '_route_context')
FUNCTIONS
get_request_handler(dependant: fastapi.dependencies.models.Dependant, body_field: fastapi._compat.v2.ModelField | None = None, status_code: int | None = None, response_class: type[starlette.responses.Response] | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54173560>, response_field: fastapi._compat.v2.ModelField | None = None, response_model_include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: typing.Any | None = None, embed_body_fields: bool = False, strict_content_type: bool | fastapi.datastructures.DefaultPlaceholder = <fastapi.datastructures.DefaultPlaceholder object at 0x0000024E54173590>, stream_item_field: fastapi._compat.v2.ModelField | None = None, is_json_stream: bool = False) -> collections.abc.Callable[[starlette.requests.Request], collections.abc.Coroutine[typing.Any, typing.Any, starlette.responses.Response]]
get_websocket_app(dependant: fastapi.dependencies.models.Dependant, dependency_overrides_provider: typing.Any | None = None, embed_body_fields: bool = False) -> collections.abc.Callable[[starlette.websockets.WebSocket], collections.abc.Coroutine[typing.Any, typing.Any, typing.Any]]
iter_route_contexts(routes: collections.abc.Sequence[starlette.routing.BaseRoute | fastapi.routing.RouteContext]) -> collections.abc.Iterator[fastapi.routing.RouteContext]
request_response(func: collections.abc.Callable[[starlette.requests.Request], collections.abc.Awaitable[starlette.responses.Response] | starlette.responses.Response]) -> collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]]
Takes a function or coroutine `func(request) -> response`,
and returns an ASGI application.
async run_endpoint_function(*, dependant: fastapi.dependencies.models.Dependant, values: dict[str, typing.Any], is_coroutine: bool) -> Any
async serialize_response(*, field: fastapi._compat.v2.ModelField | None = None, response_content: Any, include: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, exclude: Union[set[int], set[str], collections.abc.Mapping[int, Union[ForwardRef('IncEx'), bool]], collections.abc.Mapping[str, Union[ForwardRef('IncEx'), bool]], NoneType] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, endpoint_ctx: fastapi.exceptions.EndpointContext | None = None, dump_json: bool = False) -> Any
websocket_session(func: collections.abc.Callable[[starlette.websockets.WebSocket], collections.abc.Awaitable[None]]) -> collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any], collections.abc.Callable[[], collections.abc.Awaitable[collections.abc.MutableMapping[str, typing.Any]]], collections.abc.Callable[[collections.abc.MutableMapping[str, typing.Any]], collections.abc.Awaitable[None]]], collections.abc.Awaitable[None]]
Takes a coroutine `func(session)`, and returns an ASGI application.
DATA
ASGIApp = collections.abc.Callable[[collections.abc.Mutabl...aitable[N...
AppType = ~AppType
DecoratedCallable = ~DecoratedCallable
IncEx = typing.Union[set[int], set[str], collections.abc...ng[str, typ...
KEEPALIVE_COMMENT = b': ping\n\n'
Lifespan = collections.abc.Callable[[~AppType], contextlib....anager[c...
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
Receive = collections.abc.Callable[[], collections.abc.Awa...collectio...
Scope = collections.abc.MutableMapping[str, typing.Any]
Send = collections.abc.Callable[[collections.abc.Mutabl...r, typing.An...
Undefined = PydanticUndefined
__annotations__ = {'_effective_route_context_var': _contextvars.Contex...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\routing.py
fastapi.security
Python Library Documentation: package fastapi.security in fastapi
NAME
fastapi.security
PACKAGE CONTENTS
api_key
base
http
oauth2
open_id_connect_url
utils
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\security\__init__.py
fastapi.sse
Python Library Documentation: module fastapi.sse in fastapi
NAME
fastapi.sse
CLASSES
pydantic.main.BaseModel(builtins.object)
ServerSentEvent
starlette.responses.StreamingResponse(starlette.responses.Response)
EventSourceResponse
class EventSourceResponse(starlette.responses.StreamingResponse)
| EventSourceResponse(content: 'ContentStream', status_code: 'int' = 200, headers: 'Mapping[str, str] | None' = None, media_type: 'str | None' = None, background: 'BackgroundTask | None' = None) -> 'None'
|
| Streaming response with `text/event-stream` media type.
|
| Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield`
| to enable Server Sent Events (SSE) responses.
|
| Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible
| with protocols like MCP that stream SSE over `POST`.
|
| The actual encoding logic lives in the FastAPI routing layer. This class
| serves mainly as a marker and sets the correct `Content-Type`.
|
| Method resolution order:
| EventSourceResponse
| starlette.responses.StreamingResponse
| starlette.responses.Response
| builtins.object
|
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| media_type = 'text/event-stream'
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.responses.StreamingResponse:
|
| async __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> 'None'
| Call self as a function.
|
| __init__(self, content: 'ContentStream', status_code: 'int' = 200, headers: 'Mapping[str, str] | None' = None, media_type: 'str | None' = None, background: 'BackgroundTask | None' = None) -> 'None'
| Initialize self. See help(type(self)) for accurate signature.
|
| async listen_for_disconnect(self, receive: 'Receive') -> 'None'
|
| async stream_response(self, send: 'Send') -> 'None'
|
| ----------------------------------------------------------------------
| Methods inherited from starlette.responses.Response:
|
| delete_cookie(self, key: 'str', path: 'str' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: "Literal['lax', 'strict', 'none'] | None" = 'lax') -> 'None'
|
| init_headers(self, headers: 'Mapping[str, str] | None' = None) -> 'None'
|
| render(self, content: 'Any') -> 'bytes | memoryview'
|
| set_cookie(self, key: 'str', value: 'str' = '', max_age: 'int | None' = None, expires: 'datetime | str | int | None' = None, path: 'str | None' = '/', domain: 'str | None' = None, secure: 'bool' = False, httponly: 'bool' = False, samesite: "Literal['lax', 'strict', 'none'] | None" = 'lax', partitioned: 'bool' = False) -> 'None'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from starlette.responses.Response:
|
| headers
|
| ----------------------------------------------------------------------
| Data descriptors inherited from starlette.responses.Response:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from starlette.responses.Response:
|
| charset = 'utf-8'
class ServerSentEvent(pydantic.main.BaseModel)
| ServerSentEvent(*, data: Annotated[Any, Doc('\n The event payload.\n\n Can be any JSON-serializable value: a Pydantic model, dict, list,\n string, number, etc. It is **always** serialized to JSON: strings\n are quoted (`"hello"` becomes `data: "hello"` on the wire).\n\n Mutually exclusive with `raw_data`.\n ')] = None, raw_data: Annotated[str | None, Doc('\n Raw string to send as the `data:` field **without** JSON encoding.\n\n Use this when you need to send pre-formatted text, HTML fragments,\n CSV lines, or any non-JSON payload. The string is placed directly\n into the `data:` field as-is.\n\n Mutually exclusive with `data`.\n ')] = None, event: Annotated[str | None, AfterValidator(func=<function _check_event_single_line at 0x0000024E5415DD00>), Doc('\n Optional event type name.\n\n Maps to `addEventListener(event, ...)` on the browser. When omitted,\n the browser dispatches on the generic `message` event. Must be a\n single line.\n ')] = None, id: Annotated[str | None, AfterValidator(func=<function _check_id_valid at 0x0000024E5415DDA0>), Doc('\n Optional event ID.\n\n The browser sends this value back as the `Last-Event-ID` header on\n automatic reconnection. **Must be a single line** and must not contain\n null (`\\0`) characters.\n ')] = None, retry: Annotated[int | None, Ge(ge=0), Doc('\n Optional reconnection time in **milliseconds**.\n\n Tells the browser how long to wait before reconnecting after the\n connection is lost. Must be a non-negative integer.\n ')] = None, comment: Annotated[str | None, Doc('\n Optional comment line(s).\n\n Comment lines start with `:` in the SSE wire format and are ignored by\n `EventSource` clients. Useful for keep-alive pings to prevent\n proxy/load-balancer timeouts.\n ')] = None) -> None
|
| Represents a single Server-Sent Event.
|
| When `yield`ed from a *path operation function* that uses
| `response_class=EventSourceResponse`, each `ServerSentEvent` is encoded
| into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream)
| (`text/event-stream`).
|
| If you yield a plain object (dict, Pydantic model, etc.) instead, it is
| automatically JSON-encoded and sent as the `data:` field.
|
| All `data` values **including plain strings** are JSON-serialized.
|
| For example, `data="hello"` produces `data: "hello"` on the wire (with
| quotes).
|
| Method resolution order:
| ServerSentEvent
| pydantic.main.BaseModel
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __annotations__ = {'comment': typing.Annotated[str | None, Doc('\n ...
|
| __class_vars__ = set()
|
| __private_attributes__ = {}
|
| __pydantic_complete__ = True
|
| __pydantic_computed_fields__ = {}
|
| __pydantic_core_schema__ = {'function': {'function': <function ServerS...
|
| __pydantic_custom_init__ = False
|
| __pydantic_decorators__ = DecoratorInfos(validators={}, field_validato...
|
| __pydantic_extra_info__ = None
|
| __pydantic_fields__ = {'comment': FieldInfo(annotation=Union[str, None...
|
| __pydantic_generic_metadata__ = {'args': (), 'origin': None, 'paramete...
|
| __pydantic_parent_namespace__ = None
|
| __pydantic_post_init__ = None
|
| __pydantic_serializer__ = SchemaSerializer(serializer=PolymorphismTram...
|
| __pydantic_setattr_handlers__ = {}
|
| __pydantic_validator__ = SchemaValidator(title="ServerSentEvent", vali...
|
| __signature__ = <Signature (*, data: Annotated[Any, Doc('\n ...anc...
|
| model_config = {}
|
| ----------------------------------------------------------------------
| Methods inherited from pydantic.main.BaseModel:
|
| __copy__(self) -> 'Self'
| Returns a shallow copy of the model.
|
| __deepcopy__(self, memo: 'dict[int, Any] | None' = None) -> 'Self'
| Returns a deep copy of the model.
|
| __delattr__(self, item: 'str') -> 'Any'
| Implement delattr(self, name).
|
| __eq__(self, other: 'Any') -> 'bool'
| Return self==value.
|
| __getattr__(self, item: 'str') -> 'Any'
|
| __getstate__(self) -> 'dict[Any, Any]'
| Helper for pickle.
|
| __init__(self, /, **data: 'Any') -> 'None'
| Create a new model by parsing and validating input data from keyword arguments.
|
| Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
| validated to form a valid model.
|
| `self` is explicitly positional-only to allow `self` as a field name.
|
| __iter__(self) -> 'TupleGenerator'
| So `dict(model)` works.
|
| __pretty__(self, fmt: 'Callable[[Any], Any]', **kwargs: 'Any') -> 'Generator[Any]' from pydantic._internal._repr.Representation
| Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.
|
| __replace__(self, **changes: 'Any') -> 'Self'
| # Because we make use of `@dataclass_transform()`, `__replace__` is already synthesized by
| # type checkers, so we define the implementation in this `if not TYPE_CHECKING:` block:
|
| __repr__(self) -> 'str'
| Return repr(self).
|
| __repr_args__(self) -> '_repr.ReprArgs'
|
| __repr_name__(self) -> 'str' from pydantic._internal._repr.Representation
| Name of the instance's class, used in __repr__.
|
| __repr_recursion__(self, object: 'Any') -> 'str' from pydantic._internal._repr.Representation
| Returns the string representation of a recursive object.
|
| __repr_str__(self, join_str: 'str') -> 'str' from pydantic._internal._repr.Representation
|
| __rich_repr__(self) -> 'RichReprResult' from pydantic._internal._repr.Representation
| Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.
|
| __setattr__(self, name: 'str', value: 'Any') -> 'None'
| Implement setattr(self, name, value).
|
| __setstate__(self, state: 'dict[Any, Any]') -> 'None'
|
| __str__(self) -> 'str'
| Return str(self).
|
| copy(self, *, include: 'AbstractSetIntStr | MappingIntStrAny | None' = None, exclude: 'AbstractSetIntStr | MappingIntStrAny | None' = None, update: 'Dict[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| Returns a copy of the model.
|
| !!! warning "Deprecated"
| This method is now deprecated; use `model_copy` instead.
|
| If you need `include` or `exclude`, use:
|
| ```python {test="skip" lint="skip"}
| data = self.model_dump(include=include, exclude=exclude, round_trip=True)
| data = {**data, **(update or {})}
| copied = self.model_validate(data)
| ```
|
| Args:
| include: Optional set or mapping specifying which fields to include in the copied model.
| exclude: Optional set or mapping specifying which fields to exclude in the copied model.
| update: Optional dictionary of field-value pairs to override field values in the copied model.
| deep: If True, the values of fields that are Pydantic models will be deep-copied.
|
| Returns:
| A copy of the model with included, excluded and updated fields as specified.
|
| dict(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False) -> 'Dict[str, Any]'
|
| json(self, *, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, by_alias: 'bool' = False, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, encoder: 'Callable[[Any], Any] | None' = PydanticUndefined, models_as_dict: 'bool' = PydanticUndefined, **dumps_kwargs: 'Any') -> 'str'
|
| model_copy(self, *, update: 'Mapping[str, Any] | None' = None, deep: 'bool' = False) -> 'Self'
| !!! abstract "Usage Documentation"
| [`model_copy`](../concepts/models.md#model-copy)
|
| Returns a copy of the model.
|
| !!! note
| The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
| might have unexpected side effects if you store anything in it, on top of the model
| fields (e.g. the value of [cached properties][functools.cached_property]).
|
| Args:
| update: Values to change/add in the new model. Note: the data is not validated
| before creating the new model. You should trust this data.
| deep: Set to `True` to make a deep copy of the model.
|
| Returns:
| New model instance.
|
| model_dump(self, *, mode: "Literal['json', 'python'] | str" = 'python', include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'dict[str, Any]'
| !!! abstract "Usage Documentation"
| [`model_dump`](../concepts/serialization.md#python-mode)
|
| Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
|
| Args:
| mode: The mode in which `to_python` should run.
| If mode is 'json', the output will only contain JSON serializable types.
| If mode is 'python', the output may contain non-JSON-serializable Python objects.
| include: A set of fields to include in the output.
| exclude: A set of fields to exclude from the output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to use the field's alias in the dictionary key if defined.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A dictionary representation of the model.
|
| model_dump_json(self, *, indent: 'int | None' = None, ensure_ascii: 'bool' = False, include: 'IncEx | None' = None, exclude: 'IncEx | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, exclude_unset: 'bool' = False, exclude_defaults: 'bool' = False, exclude_none: 'bool' = False, exclude_computed_fields: 'bool' = False, round_trip: 'bool' = False, warnings: "bool | Literal['none', 'warn', 'error']" = True, fallback: 'Callable[[Any], Any] | None' = None, serialize_as_any: 'bool' = False, polymorphic_serialization: 'bool | None' = None) -> 'str'
| !!! abstract "Usage Documentation"
| [`model_dump_json`](../concepts/serialization.md#json-mode)
|
| Generates a JSON representation of the model using Pydantic's `to_json` method.
|
| Args:
| indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
| ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
| If `False` (the default), these characters will be output as-is.
| include: Field(s) to include in the JSON output.
| exclude: Field(s) to exclude from the JSON output.
| context: Additional context to pass to the serializer.
| by_alias: Whether to serialize using field aliases.
| exclude_unset: Whether to exclude fields that have not been explicitly set.
| exclude_defaults: Whether to exclude fields that are set to their default value.
| exclude_none: Whether to exclude fields that have a value of `None`.
| exclude_computed_fields: Whether to exclude computed fields.
| While this can be useful for round-tripping, it is usually recommended to use the dedicated
| `round_trip` parameter instead.
| round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
| warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
| "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
| fallback: A function to call when an unknown value is encountered. If not provided,
| a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
| serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
| polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
|
| Returns:
| A JSON string representation of the model.
|
| model_post_init(self, context: 'Any', /) -> 'None'
| Override this method to perform additional initialization after `__init__` and `model_construct`.
| This is useful if you want to do some validation that requires the entire model to be initialized.
|
| ----------------------------------------------------------------------
| Class methods inherited from pydantic.main.BaseModel:
|
| __class_getitem__(typevar_values: 'type[Any] | tuple[type[Any], ...]') -> 'type[BaseModel] | _forward_ref.PydanticRecursiveRef'
|
| __get_pydantic_core_schema__(source: 'type[BaseModel]', handler: 'GetCoreSchemaHandler', /) -> 'CoreSchema'
|
| __get_pydantic_json_schema__(core_schema: 'CoreSchema', handler: 'GetJsonSchemaHandler', /) -> 'JsonSchemaValue'
| Hook into generating the model's JSON schema.
|
| Args:
| core_schema: A `pydantic-core` CoreSchema.
| You can ignore this argument and call the handler with a new CoreSchema,
| wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
| or just call the handler with the original schema.
| handler: Call into Pydantic's internal JSON schema generation.
| This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
| generation fails.
| Since this gets called by `BaseModel.model_json_schema` you can override the
| `schema_generator` argument to that function to change JSON schema generation globally
| for a type.
|
| Returns:
| A JSON schema, as a Python object.
|
| __pydantic_init_subclass__(**kwargs: 'Any') -> 'None'
| This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
| only after basic class initialization is complete. In particular, attributes like `model_fields` will
| be present when this is called, but forward annotations are not guaranteed to be resolved yet,
| meaning that creating an instance of the class may fail.
|
| This is necessary because `__init_subclass__` will always be called by `type.__new__`,
| and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
| `type.__new__` was called in such a manner that the class would already be sufficiently initialized.
|
| This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
| any kwargs passed to the class definition that aren't used internally by Pydantic.
|
| Args:
| **kwargs: Any keyword arguments passed to the class definition that aren't used internally
| by Pydantic.
|
| Note:
| You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
| instead, which is called once the class and its fields are fully initialized and ready for validation.
|
| __pydantic_on_complete__() -> 'None'
| This is called once the class and its fields are fully initialized and ready to be used.
|
| This typically happens when the class is created (just before
| [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
| except when forward annotations are used that could not immediately be resolved.
| In that case, it will be called later, when the model is rebuilt automatically or explicitly using
| [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
|
| construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
|
| from_orm(obj: 'Any') -> 'Self'
|
| model_construct(_fields_set: 'set[str] | None' = None, **values: 'Any') -> 'Self'
| Creates a new instance of the `Model` class with validated data.
|
| Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
| Default values are respected, but no other validation is performed.
|
| !!! note
| `model_construct()` generally respects the `model_config.extra` setting on the provided model.
| That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
| and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
| Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
| an error if extra values are passed, but they will be ignored.
|
| Args:
| _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
| this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
| Otherwise, the field names from the `values` argument will be used.
| values: Trusted or pre-validated data dictionary.
|
| Returns:
| A new instance of the `Model` class with validated data.
|
| model_json_schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', schema_generator: 'type[GenerateJsonSchema]' = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: 'JsonSchemaMode' = 'validation', *, union_format: "Literal['any_of', 'primitive_type_array']" = 'any_of') -> 'dict[str, Any]'
| Generates a JSON schema for a model class.
|
| Args:
| by_alias: Whether to use attribute aliases or not.
| ref_template: The reference template.
| union_format: The format to use when combining schemas from unions together. Can be one of:
|
| - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
| keyword to combine schemas (the default).
| - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
| keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
| type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
| `any_of`.
| schema_generator: To override the logic used to generate the JSON schema, as a subclass of
| `GenerateJsonSchema` with your desired modifications
| mode: The mode in which to generate the schema.
|
| Returns:
| The JSON schema for the given model class.
|
| model_parametrized_name(params: 'tuple[type[Any], ...]') -> 'str'
| Compute the class name for parametrizations of generic classes.
|
| This method can be overridden to achieve a custom naming scheme for generic BaseModels.
|
| Args:
| params: Tuple of types of the class. Given a generic class
| `Model` with 2 type variables and a concrete model `Model[str, int]`,
| the value `(str, int)` would be passed to `params`.
|
| Returns:
| String representing the new class where `params` are passed to `cls` as type variables.
|
| Raises:
| TypeError: Raised when trying to generate concrete names for non-generic models.
|
| model_rebuild(*, force: 'bool' = False, raise_errors: 'bool' = True, _parent_namespace_depth: 'int' = 2, _types_namespace: 'MappingNamespace | None' = None) -> 'bool | None'
| Try to rebuild the pydantic-core schema for the model.
|
| This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
| the initial attempt to build the schema, and automatic rebuilding fails.
|
| Args:
| force: Whether to force the rebuilding of the model schema, defaults to `False`.
| raise_errors: Whether to raise errors, defaults to `True`.
| _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
| _types_namespace: The types namespace, defaults to `None`.
|
| Returns:
| Returns `None` if the schema is already "complete" and rebuilding was not required.
| If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
|
| model_validate(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, from_attributes: 'bool | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate a pydantic model instance.
|
| Args:
| obj: The object to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| from_attributes: Whether to extract data from object attributes.
| context: Additional context to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Raises:
| ValidationError: If the object could not be validated.
|
| Returns:
| The validated model instance.
|
| model_validate_json(json_data: 'str | bytes | bytearray', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| !!! abstract "Usage Documentation"
| [JSON Parsing](../concepts/json.md#json-parsing)
|
| Validate the given JSON data against the Pydantic model.
|
| Args:
| json_data: The JSON data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| Raises:
| ValidationError: If `json_data` is not a JSON string or the object could not be validated.
|
| model_validate_strings(obj: 'Any', *, strict: 'bool | None' = None, extra: 'ExtraValues | None' = None, context: 'Any | None' = None, by_alias: 'bool | None' = None, by_name: 'bool | None' = None) -> 'Self'
| Validate the given object with string data against the Pydantic model.
|
| Args:
| obj: The object containing string data to validate.
| strict: Whether to enforce types strictly.
| extra: Whether to ignore, allow, or forbid extra data during model validation.
| See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
| context: Extra variables to pass to the validator.
| by_alias: Whether to use the field's alias when validating against the provided input data.
| by_name: Whether to use the field's name when validating against the provided input data.
|
| Returns:
| The validated Pydantic model.
|
| parse_file(path: 'str | Path', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| parse_obj(obj: 'Any') -> 'Self'
|
| parse_raw(b: 'str | bytes', *, content_type: 'str | None' = None, encoding: 'str' = 'utf8', proto: 'DeprecatedParseProtocol | None' = None, allow_pickle: 'bool' = False) -> 'Self'
|
| schema(by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}') -> 'Dict[str, Any]'
|
| schema_json(*, by_alias: 'bool' = True, ref_template: 'str' = '#/$defs/{model}', **dumps_kwargs: 'Any') -> 'str'
|
| update_forward_refs(**localns: 'Any') -> 'None'
|
| validate(value: 'Any') -> 'Self'
|
| ----------------------------------------------------------------------
| Readonly properties inherited from pydantic.main.BaseModel:
|
| __fields_set__
|
| model_extra
| Get extra fields set during validation.
|
| Returns:
| A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.
|
| model_fields_set
| Returns the set of fields that have been explicitly set on this model instance.
|
| Returns:
| A set of strings representing the fields that have been set,
| i.e. that were not filled from defaults.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from pydantic.main.BaseModel:
|
| __dict__
| dictionary for instance variables
|
| __pydantic_extra__
|
| __pydantic_fields_set__
|
| __pydantic_private__
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from pydantic.main.BaseModel:
|
| __hash__ = None
|
| __pydantic_root_model__ = False
|
| model_computed_fields = {}
|
| model_fields = {'comment': FieldInfo(annotation=Union[str, NoneType], ...
FUNCTIONS
format_sse_event(*, data_str: Annotated[str | None, Doc('\n Pre-serialized data string to use as the `data:` field.\n ')] = None, event: Annotated[str | None, Doc('\n Optional event type name (`event:` field).\n ')] = None, id: Annotated[str | None, Doc('\n Optional event ID (`id:` field).\n ')] = None, retry: Annotated[int | None, Doc('\n Optional reconnection time in milliseconds (`retry:` field).\n ')] = None, comment: Annotated[str | None, Doc('\n Optional comment line(s) (`:` prefix).\n ')] = None) -> bytes
Build SSE wire-format bytes from **pre-serialized** data.
The result always ends with `\n\n` (the event terminator).
DATA
KEEPALIVE_COMMENT = b': ping\n\n'
__annotations__ = {'_PING_INTERVAL': <class 'float'>, '_SSE_EVENT_SCHE...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\sse.py
fastapi.status
Python Library Documentation: module starlette.status in starlette
NAME
starlette.status
DESCRIPTION
HTTP codes
See HTTP Status Code Registry:
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
And RFC 9110 - https://www.rfc-editor.org/rfc/rfc9110
DATA
HTTP_100_CONTINUE = 100
HTTP_101_SWITCHING_PROTOCOLS = 101
HTTP_102_PROCESSING = 102
HTTP_103_EARLY_HINTS = 103
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_202_ACCEPTED = 202
HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
HTTP_204_NO_CONTENT = 204
HTTP_205_RESET_CONTENT = 205
HTTP_206_PARTIAL_CONTENT = 206
HTTP_207_MULTI_STATUS = 207
HTTP_208_ALREADY_REPORTED = 208
HTTP_226_IM_USED = 226
HTTP_300_MULTIPLE_CHOICES = 300
HTTP_301_MOVED_PERMANENTLY = 301
HTTP_302_FOUND = 302
HTTP_303_SEE_OTHER = 303
HTTP_304_NOT_MODIFIED = 304
HTTP_305_USE_PROXY = 305
HTTP_306_RESERVED = 306
HTTP_307_TEMPORARY_REDIRECT = 307
HTTP_308_PERMANENT_REDIRECT = 308
HTTP_400_BAD_REQUEST = 400
HTTP_401_UNAUTHORIZED = 401
HTTP_402_PAYMENT_REQUIRED = 402
HTTP_403_FORBIDDEN = 403
HTTP_404_NOT_FOUND = 404
HTTP_405_METHOD_NOT_ALLOWED = 405
HTTP_406_NOT_ACCEPTABLE = 406
HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407
HTTP_408_REQUEST_TIMEOUT = 408
HTTP_409_CONFLICT = 409
HTTP_410_GONE = 410
HTTP_411_LENGTH_REQUIRED = 411
HTTP_412_PRECONDITION_FAILED = 412
HTTP_413_CONTENT_TOO_LARGE = 413
HTTP_414_URI_TOO_LONG = 414
HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
HTTP_416_RANGE_NOT_SATISFIABLE = 416
HTTP_417_EXPECTATION_FAILED = 417
HTTP_418_IM_A_TEAPOT = 418
HTTP_421_MISDIRECTED_REQUEST = 421
HTTP_422_UNPROCESSABLE_CONTENT = 422
HTTP_423_LOCKED = 423
HTTP_424_FAILED_DEPENDENCY = 424
HTTP_425_TOO_EARLY = 425
HTTP_426_UPGRADE_REQUIRED = 426
HTTP_428_PRECONDITION_REQUIRED = 428
HTTP_429_TOO_MANY_REQUESTS = 429
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451
HTTP_500_INTERNAL_SERVER_ERROR = 500
HTTP_501_NOT_IMPLEMENTED = 501
HTTP_502_BAD_GATEWAY = 502
HTTP_503_SERVICE_UNAVAILABLE = 503
HTTP_504_GATEWAY_TIMEOUT = 504
HTTP_505_HTTP_VERSION_NOT_SUPPORTED = 505
HTTP_506_VARIANT_ALSO_NEGOTIATES = 506
HTTP_507_INSUFFICIENT_STORAGE = 507
HTTP_508_LOOP_DETECTED = 508
HTTP_510_NOT_EXTENDED = 510
HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = 511
WS_1000_NORMAL_CLOSURE = 1000
WS_1001_GOING_AWAY = 1001
WS_1002_PROTOCOL_ERROR = 1002
WS_1003_UNSUPPORTED_DATA = 1003
WS_1005_NO_STATUS_RCVD = 1005
WS_1006_ABNORMAL_CLOSURE = 1006
WS_1007_INVALID_FRAME_PAYLOAD_DATA = 1007
WS_1008_POLICY_VIOLATION = 1008
WS_1009_MESSAGE_TOO_BIG = 1009
WS_1010_MANDATORY_EXT = 1010
WS_1011_INTERNAL_ERROR = 1011
WS_1012_SERVICE_RESTART = 1012
WS_1013_TRY_AGAIN_LATER = 1013
WS_1014_BAD_GATEWAY = 1014
WS_1015_TLS_HANDSHAKE = 1015
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\starlette\status.py
fastapi.types
Python Library Documentation: module fastapi.types in fastapi
NAME
fastapi.types
DATA
DecoratedCallable = ~DecoratedCallable
DependencyCacheKey = tuple[collections.abc.Callable[..., typing.Any] |...
IncEx = typing.Union[set[int], set[str], collections.abc...ng[str, typ...
ModelNameMap = dict[type[pydantic.main.BaseModel] | type[enum.Enum], s...
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\types.py
fastapi.utils
Python Library Documentation: module fastapi.utils in fastapi
NAME
fastapi.utils
FUNCTIONS
create_model_field(name: str, type_: Any, default: typing.Any | None = PydanticUndefined, field_info: pydantic.fields.FieldInfo | None = None, alias: str | None = None, mode: Literal['validation', 'serialization'] = 'validation') -> fastapi._compat.v2.ModelField
deep_dict_update(main_dict: dict[typing.Any, typing.Any], update_dict: dict[typing.Any, typing.Any]) -> None
generate_operation_id_for_path(*, name: str, path: str, method: str) -> str
generate_unique_id(route: 'APIRoute') -> str
get_path_param_names(path: str) -> set[str]
get_value_or_default(first_item: Union[fastapi.datastructures.DefaultPlaceholder, ~DefaultType], *extra_items: Union[fastapi.datastructures.DefaultPlaceholder, ~DefaultType]) -> Union[fastapi.datastructures.DefaultPlaceholder, ~DefaultType]
Pass items or `DefaultPlaceholder`s by descending priority.
The first one to _not_ be a `DefaultPlaceholder` will be returned.
Otherwise, the first item (a `DefaultPlaceholder`) will be returned.
is_body_allowed_for_status_code(status_code: int | str | None) -> bool
DATA
DefaultType = ~DefaultType
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
TYPE_CHECKING = False
Undefined = PydanticUndefined
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\utils.py
fastapi.websockets
Python Library Documentation: module fastapi.websockets in fastapi
NAME
fastapi.websockets
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\site-packages\fastapi\websockets.py