from typing import (
Annotated,
Any,
+ Literal,
Union,
cast,
+ get_args,
+ get_origin,
)
from fastapi._compat import lenient_issubclass, shared
from pydantic_core.core_schema import (
with_info_plain_validator_function as with_info_plain_validator_function,
)
-from typing_extensions import Literal, get_args, get_origin
RequiredParam = PydanticUndefined
Undefined = PydanticUndefined
field_info: FieldInfo
name: str
mode: Literal["validation", "serialization"] = "validation"
- config: Union[ConfigDict, None] = None
+ config: ConfigDict | None = None
@property
def alias(self) -> str:
return a if a is not None else self.name
@property
- def validation_alias(self) -> Union[str, None]:
+ def validation_alias(self) -> str | None:
va = self.field_info.validation_alias
if isinstance(va, str) and va:
return va
return None
@property
- def serialization_alias(self) -> Union[str, None]:
+ def serialization_alias(self) -> str | None:
sa = self.field_info.serialization_alias
return sa or None
value: Any,
values: dict[str, Any] = {}, # noqa: B006
*,
- loc: tuple[Union[int, str], ...] = (),
+ loc: tuple[int | str, ...] = (),
) -> tuple[Any, list[dict[str, Any]]]:
try:
return (
value: Any,
*,
mode: Literal["json", "python"] = "json",
- include: Union[IncEx, None] = None,
- exclude: Union[IncEx, None] = None,
+ include: IncEx | None = None,
+ exclude: IncEx | None = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
],
separate_input_output_schemas: bool = True,
) -> dict[str, Any]:
- override_mode: Union[Literal["validation"], None] = (
+ override_mode: Literal["validation"] | None = (
None
if (separate_input_output_schemas or _has_computed_fields(field))
else "validation"
return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index]
-def get_missing_field_error(loc: tuple[Union[int, str], ...]) -> dict[str, Any]:
+def get_missing_field_error(loc: tuple[int | str, ...]) -> dict[str, Any]:
error = ValidationError.from_exception_data(
"Field required", [{"type": "missing", "loc": loc, "input": {}}]
).errors(include_url=False)[0]
# Duplicate of several schema functions from Pydantic v1 to make them compatible with
# Pydantic v2 and allow mixing the models
-TypeModelOrEnum = Union[type["BaseModel"], type[Enum]]
+TypeModelOrEnum = type["BaseModel"] | type[Enum]
TypeModelSet = set[TypeModelOrEnum]
def get_flat_models_from_model(
- model: type["BaseModel"], known_models: Union[TypeModelSet, None] = None
+ model: type["BaseModel"], known_models: TypeModelSet | None = None
) -> TypeModelSet:
known_models = known_models or set()
fields = get_model_fields(model)
def _regenerate_error_with_loc(
- *, errors: Sequence[Any], loc_prefix: tuple[Union[str, int], ...]
+ *, errors: Sequence[Any], loc_prefix: tuple[str | int, ...]
) -> list[dict[str, Any]]:
updated_loc_errors: list[Any] = [
{**err, "loc": loc_prefix + err.get("loc", ())} for err in errors
-from collections.abc import Awaitable, Coroutine, Sequence
+from collections.abc import Awaitable, Callable, Coroutine, Sequence
from enum import Enum
from typing import (
Annotated,
Any,
- Callable,
- Optional,
TypeVar,
- Union,
)
from annotated_doc import Doc
),
] = False,
routes: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
**Note**: you probably shouldn't use this parameter, it is inherited
),
] = "FastAPI",
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A short summary of the API.
),
] = "0.1.0",
openapi_url: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The URL where the OpenAPI schema will be served from.
),
] = "/openapi.json",
openapi_tags: Annotated[
- Optional[list[dict[str, Any]]],
+ list[dict[str, Any]] | None,
Doc(
"""
A list of tags used by OpenAPI, these are the same `tags` you can set
),
] = None,
servers: Annotated[
- Optional[list[dict[str, Union[str, Any]]]],
+ list[dict[str, str | Any]] | None,
Doc(
"""
A `list` of `dict`s with connectivity information to a target server.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of global dependencies, they will be applied to each
),
] = True,
docs_url: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The path to the automatic interactive API documentation.
),
] = "/docs",
redoc_url: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The path to the alternative automatic interactive API documentation
),
] = "/redoc",
swagger_ui_oauth2_redirect_url: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The OAuth2 redirect endpoint for the Swagger UI.
),
] = "/docs/oauth2-redirect",
swagger_ui_init_oauth: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
OAuth2 configuration for the Swagger UI, by default shown at `/docs`.
),
] = None,
middleware: Annotated[
- Optional[Sequence[Middleware]],
+ Sequence[Middleware] | None,
Doc(
"""
List of middleware to be added when creating the application.
),
] = None,
exception_handlers: Annotated[
- Optional[
- dict[
- Union[int, type[Exception]],
- Callable[[Request, Any], Coroutine[Any, Any, Response]],
- ]
- ],
+ dict[
+ int | type[Exception],
+ Callable[[Request, Any], Coroutine[Any, Any, Response]],
+ ]
+ | None,
Doc(
"""
A dictionary with handlers for exceptions.
),
] = None,
on_startup: Annotated[
- Optional[Sequence[Callable[[], Any]]],
+ Sequence[Callable[[], Any]] | None,
Doc(
"""
A list of startup event handler functions.
),
] = None,
on_shutdown: Annotated[
- Optional[Sequence[Callable[[], Any]]],
+ Sequence[Callable[[], Any]] | None,
Doc(
"""
A list of shutdown event handler functions.
),
] = None,
lifespan: Annotated[
- Optional[Lifespan[AppType]],
+ Lifespan[AppType] | None,
Doc(
"""
A `Lifespan` context manager handler. This replaces `startup` and
),
] = None,
terms_of_service: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A URL to the Terms of Service for your API.
),
] = None,
contact: Annotated[
- Optional[dict[str, Union[str, Any]]],
+ dict[str, str | Any] | None,
Doc(
"""
A dictionary with the contact information for the exposed API.
),
] = None,
license_info: Annotated[
- Optional[dict[str, Union[str, Any]]],
+ dict[str, str | Any] | None,
Doc(
"""
A dictionary with the license information for the exposed API.
),
] = True,
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses to be shown in OpenAPI.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
OpenAPI callbacks that should apply to all *path operations*.
),
] = None,
webhooks: Annotated[
- Optional[routing.APIRouter],
+ routing.APIRouter | None,
Doc(
"""
Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark all *path operations* as deprecated. You probably don't need it,
),
] = True,
swagger_ui_parameters: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Parameters to configure Swagger UI, the autogenerated interactive API
),
] = True,
openapi_external_docs: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
This field allows you to provide additional external documentation links.
"""
),
] = "3.1.0"
- self.openapi_schema: Optional[dict[str, Any]] = None
+ self.openapi_schema: dict[str, Any] | None = None
if self.openapi_url:
assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'"
generate_unique_id_function=generate_unique_id_function,
)
self.exception_handlers: dict[
- Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]
+ Any, Callable[[Request, Any], Response | Awaitable[Response]]
] = {} if exception_handlers is None else dict(exception_handlers)
self.exception_handlers.setdefault(HTTPException, http_exception_handler)
self.exception_handlers.setdefault(
self.user_middleware: list[Middleware] = (
[] if middleware is None else list(middleware)
)
- self.middleware_stack: Union[ASGIApp, None] = None
+ self.middleware_stack: ASGIApp | None = None
self.setup()
def build_middleware_stack(self) -> ASGIApp:
endpoint: Callable[..., Any],
*,
response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[list[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
+ status_code: int | None = None,
+ tags: list[str | Enum] | None = None,
+ dependencies: Sequence[Depends] | None = None,
+ summary: str | None = None,
+ description: str | None = None,
response_description: str = "Successful Response",
- responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- methods: Optional[list[str]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
+ responses: dict[int | str, dict[str, Any]] | None = None,
+ deprecated: bool | None = None,
+ methods: list[str] | None = None,
+ operation_id: str | None = None,
+ response_model_include: IncEx | None = None,
+ response_model_exclude: IncEx | None = 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: Union[type[Response], DefaultPlaceholder] = Default(
- JSONResponse
- ),
- name: Optional[str] = None,
- openapi_extra: Optional[dict[str, Any]] = None,
+ response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
+ name: str | None = None,
+ openapi_extra: dict[str, Any] | None = None,
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
generate_unique_id
),
path: str,
*,
response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[list[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
+ status_code: int | None = None,
+ tags: list[str | Enum] | None = None,
+ dependencies: Sequence[Depends] | None = None,
+ summary: str | None = None,
+ description: str | None = None,
response_description: str = "Successful Response",
- responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- methods: Optional[list[str]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
+ responses: dict[int | str, dict[str, Any]] | None = None,
+ deprecated: bool | None = None,
+ methods: list[str] | None = None,
+ operation_id: str | None = None,
+ response_model_include: IncEx | None = None,
+ response_model_exclude: IncEx | None = 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[Response] = Default(JSONResponse),
- name: Optional[str] = None,
- openapi_extra: Optional[dict[str, Any]] = None,
+ name: str | None = None,
+ openapi_extra: dict[str, Any] | None = None,
generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(
generate_unique_id
),
self,
path: str,
endpoint: Callable[..., Any],
- name: Optional[str] = None,
+ name: str | None = None,
*,
- dependencies: Optional[Sequence[Depends]] = None,
+ dependencies: Sequence[Depends] | None = None,
) -> None:
self.router.add_api_websocket_route(
path,
),
],
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A name for the WebSocket. Only used internally.
] = None,
*,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be used for this
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to all the *path operations* in this
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to all the
),
] = None,
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses to be shown in OpenAPI.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark all the *path operations* in this router as deprecated.
),
] = Default(JSONResponse),
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[Depends]],
+ Sequence[Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
)
def websocket_route(
- self, path: str, name: Union[str, None] = None
+ self, path: str, name: str | None = None
) -> Callable[[DecoratedCallable], DecoratedCallable]:
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.router.add_websocket_route(path, func, name=name)
def exception_handler(
self,
exc_class_or_status_code: Annotated[
- Union[int, type[Exception]],
+ int | type[Exception],
Doc(
"""
The Exception class this would handle, or a status code.
-from typing import Annotated, Any, Callable
+from collections.abc import Callable
+from typing import Annotated, Any
from annotated_doc import Doc
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
-from collections.abc import Mapping
+from collections.abc import Callable, Mapping
from typing import (
Annotated,
Any,
BinaryIO,
- Callable,
- Optional,
TypeVar,
cast,
)
BinaryIO,
Doc("The standard Python file object (non-async)."),
]
- filename: Annotated[Optional[str], Doc("The original file name.")]
- size: Annotated[Optional[int], Doc("The size of the file in bytes.")]
+ filename: Annotated[str | None, Doc("The original file name.")]
+ size: Annotated[int | None, Doc("The size of the file in bytes.")]
headers: Annotated[Headers, Doc("The headers of the request.")]
content_type: Annotated[
- Optional[str], Doc("The content type of the request, from the headers.")
+ str | None, Doc("The content type of the request, from the headers.")
]
async def write(
import inspect
import sys
+from collections.abc import Callable
from dataclasses import dataclass, field
from functools import cached_property, partial
-from typing import Any, Callable, Optional, Union
+from typing import Any, Literal
from fastapi._compat import ModelField
from fastapi.security.base import SecurityBase
from fastapi.types import DependencyCacheKey
-from typing_extensions import Literal
if sys.version_info >= (3, 13): # pragma: no cover
from inspect import iscoroutinefunction
from asyncio import iscoroutinefunction
-def _unwrapped_call(call: Optional[Callable[..., Any]]) -> Any:
+def _unwrapped_call(call: Callable[..., Any] | None) -> Any:
if call is None:
return call # pragma: no cover
unwrapped = inspect.unwrap(_impartial(call))
cookie_params: list[ModelField] = field(default_factory=list)
body_params: list[ModelField] = field(default_factory=list)
dependencies: list["Dependant"] = field(default_factory=list)
- name: Optional[str] = None
- call: Optional[Callable[..., Any]] = None
- request_param_name: Optional[str] = None
- websocket_param_name: Optional[str] = None
- http_connection_param_name: Optional[str] = None
- response_param_name: Optional[str] = None
- background_tasks_param_name: Optional[str] = None
- security_scopes_param_name: Optional[str] = None
- own_oauth_scopes: Optional[list[str]] = None
- parent_oauth_scopes: Optional[list[str]] = None
+ name: str | None = None
+ call: Callable[..., Any] | None = None
+ request_param_name: str | None = None
+ websocket_param_name: str | None = None
+ http_connection_param_name: str | None = None
+ response_param_name: str | None = None
+ background_tasks_param_name: str | None = None
+ security_scopes_param_name: str | None = None
+ own_oauth_scopes: list[str] | None = None
+ parent_oauth_scopes: list[str] | None = None
use_cache: bool = True
- path: Optional[str] = None
- scope: Union[Literal["function", "request"], None] = None
+ path: str | None = None
+ scope: Literal["function", "request"] | None = None
@cached_property
def oauth_scopes(self) -> list[str]:
return False
@cached_property
- def computed_scope(self) -> Union[str, None]:
+ def computed_scope(self) -> str | None:
if self.scope:
return self.scope
if self.is_gen_callable or self.is_async_gen_callable:
import dataclasses
import datetime
from collections import defaultdict, deque
+from collections.abc import Callable
from decimal import Decimal
from enum import Enum
from ipaddress import (
from pathlib import Path, PurePath
from re import Pattern
from types import GeneratorType
-from typing import Annotated, Any, Callable, Optional, Union
+from typing import Annotated, Any
from uuid import UUID
from annotated_doc import Doc
# Taken from Pydantic v1 as is
-def isoformat(o: Union[datetime.date, datetime.time]) -> str:
+def isoformat(o: datetime.date | datetime.time) -> str:
return o.isoformat()
# Adapted from Pydantic v1
# TODO: pv2 should this return strings instead?
-def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
+def decimal_encoder(dec_value: Decimal) -> int | float:
"""
Encodes a Decimal as int if there's no exponent, otherwise float
),
],
include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Pydantic's `include` parameter, passed to Pydantic models to set the
),
] = None,
exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Pydantic's `exclude` parameter, passed to Pydantic models to set the
),
] = False,
custom_encoder: Annotated[
- Optional[dict[Any, Callable[[Any], Any]]],
+ dict[Any, Callable[[Any], Any]] | None,
Doc(
"""
Pydantic's `custom_encoder` parameter, passed to Pydantic models to define
from collections.abc import Mapping, Sequence
-from typing import Annotated, Any, Optional, TypedDict, Union
+from typing import Annotated, Any, TypedDict
from annotated_doc import Doc
from pydantic import BaseModel, create_model
),
] = None,
headers: Annotated[
- Optional[Mapping[str, str]],
+ Mapping[str, str] | None,
Doc(
"""
Any headers to send to the client in the response.
),
],
reason: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
The reason to close the WebSocket connection.
self,
errors: Sequence[Any],
*,
- endpoint_ctx: Optional[EndpointContext] = None,
+ endpoint_ctx: EndpointContext | None = None,
) -> None:
self._errors = errors
self.endpoint_ctx = endpoint_ctx
errors: Sequence[Any],
*,
body: Any = None,
- endpoint_ctx: Optional[EndpointContext] = None,
+ endpoint_ctx: EndpointContext | None = None,
) -> None:
super().__init__(errors, endpoint_ctx=endpoint_ctx)
self.body = body
self,
errors: Sequence[Any],
*,
- endpoint_ctx: Optional[EndpointContext] = None,
+ endpoint_ctx: EndpointContext | None = None,
) -> None:
super().__init__(errors, endpoint_ctx=endpoint_ctx)
errors: Sequence[Any],
*,
body: Any = None,
- endpoint_ctx: Optional[EndpointContext] = None,
+ endpoint_ctx: EndpointContext | None = None,
) -> None:
super().__init__(errors, endpoint_ctx=endpoint_ctx)
self.body = body
import json
-from typing import Annotated, Any, Optional
+from typing import Annotated, Any
from annotated_doc import Doc
from fastapi.encoders import jsonable_encoder
),
] = "https://fastapi.tiangolo.com/img/favicon.png",
oauth2_redirect_url: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The OAuth2 redirect URL, it is normally automatically handled by FastAPI.
),
] = None,
init_oauth: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
A dictionary with Swagger UI OAuth2 initialization configurations.
),
] = None,
swagger_ui_parameters: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Configuration parameters for Swagger UI.
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from enum import Enum
-from typing import Annotated, Any, Callable, Optional, Union
+from typing import Annotated, Any, Literal, Optional, Union
from fastapi._compat import with_info_plain_validator_function
from fastapi.logger import logger
Field,
GetJsonSchemaHandler,
)
-from typing_extensions import Literal, TypedDict
+from typing_extensions import TypedDict
from typing_extensions import deprecated as typing_deprecated
try:
class Contact(BaseModelWithConfig):
- name: Optional[str] = None
- url: Optional[AnyUrl] = None
- email: Optional[EmailStr] = None
+ name: str | None = None
+ url: AnyUrl | None = None
+ email: EmailStr | None = None
class License(BaseModelWithConfig):
name: str
- identifier: Optional[str] = None
- url: Optional[AnyUrl] = None
+ identifier: str | None = None
+ url: AnyUrl | None = None
class Info(BaseModelWithConfig):
title: str
- summary: Optional[str] = None
- description: Optional[str] = None
- termsOfService: Optional[str] = None
- contact: Optional[Contact] = None
- license: Optional[License] = None
+ summary: str | None = None
+ description: str | None = None
+ termsOfService: str | None = None
+ contact: Contact | None = None
+ license: License | None = None
version: str
class ServerVariable(BaseModelWithConfig):
- enum: Annotated[Optional[list[str]], Field(min_length=1)] = None
+ enum: Annotated[list[str] | None, Field(min_length=1)] = None
default: str
- description: Optional[str] = None
+ description: str | None = None
class Server(BaseModelWithConfig):
- url: Union[AnyUrl, str]
- description: Optional[str] = None
- variables: Optional[dict[str, ServerVariable]] = None
+ url: AnyUrl | str
+ description: str | None = None
+ variables: dict[str, ServerVariable] | None = None
class Reference(BaseModel):
class Discriminator(BaseModel):
propertyName: str
- mapping: Optional[dict[str, str]] = None
+ mapping: dict[str, str] | None = None
class XML(BaseModelWithConfig):
- name: Optional[str] = None
- namespace: Optional[str] = None
- prefix: Optional[str] = None
- attribute: Optional[bool] = None
- wrapped: Optional[bool] = None
+ name: str | None = None
+ namespace: str | None = None
+ prefix: str | None = None
+ attribute: bool | None = None
+ wrapped: bool | None = None
class ExternalDocumentation(BaseModelWithConfig):
- description: Optional[str] = None
+ description: str | None = None
url: AnyUrl
class Schema(BaseModelWithConfig):
# Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu
# Core Vocabulary
- schema_: Optional[str] = Field(default=None, alias="$schema")
- vocabulary: Optional[str] = Field(default=None, alias="$vocabulary")
- id: Optional[str] = Field(default=None, alias="$id")
- anchor: Optional[str] = Field(default=None, alias="$anchor")
- dynamicAnchor: Optional[str] = Field(default=None, alias="$dynamicAnchor")
- ref: Optional[str] = Field(default=None, alias="$ref")
- dynamicRef: Optional[str] = Field(default=None, alias="$dynamicRef")
- defs: Optional[dict[str, "SchemaOrBool"]] = Field(default=None, alias="$defs")
- comment: Optional[str] = Field(default=None, alias="$comment")
+ schema_: str | None = Field(default=None, alias="$schema")
+ vocabulary: str | None = Field(default=None, alias="$vocabulary")
+ id: str | None = Field(default=None, alias="$id")
+ anchor: str | None = Field(default=None, alias="$anchor")
+ dynamicAnchor: str | None = Field(default=None, alias="$dynamicAnchor")
+ ref: str | None = Field(default=None, alias="$ref")
+ dynamicRef: str | None = Field(default=None, alias="$dynamicRef")
+ defs: dict[str, "SchemaOrBool"] | None = Field(default=None, alias="$defs")
+ comment: str | None = Field(default=None, alias="$comment")
# Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-a-vocabulary-for-applying-s
# A Vocabulary for Applying Subschemas
- allOf: Optional[list["SchemaOrBool"]] = None
- anyOf: Optional[list["SchemaOrBool"]] = None
- oneOf: Optional[list["SchemaOrBool"]] = None
+ allOf: list["SchemaOrBool"] | None = None
+ anyOf: list["SchemaOrBool"] | None = None
+ oneOf: list["SchemaOrBool"] | None = None
not_: Optional["SchemaOrBool"] = Field(default=None, alias="not")
if_: Optional["SchemaOrBool"] = Field(default=None, alias="if")
then: Optional["SchemaOrBool"] = None
else_: Optional["SchemaOrBool"] = Field(default=None, alias="else")
- dependentSchemas: Optional[dict[str, "SchemaOrBool"]] = None
- prefixItems: Optional[list["SchemaOrBool"]] = None
+ dependentSchemas: dict[str, "SchemaOrBool"] | None = None
+ prefixItems: list["SchemaOrBool"] | None = None
items: Optional["SchemaOrBool"] = None
contains: Optional["SchemaOrBool"] = None
- properties: Optional[dict[str, "SchemaOrBool"]] = None
- patternProperties: Optional[dict[str, "SchemaOrBool"]] = None
+ properties: dict[str, "SchemaOrBool"] | None = None
+ patternProperties: dict[str, "SchemaOrBool"] | None = None
additionalProperties: Optional["SchemaOrBool"] = None
propertyNames: Optional["SchemaOrBool"] = None
unevaluatedItems: Optional["SchemaOrBool"] = None
unevaluatedProperties: Optional["SchemaOrBool"] = None
# Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural
# A Vocabulary for Structural Validation
- type: Optional[Union[SchemaType, list[SchemaType]]] = None
- enum: Optional[list[Any]] = None
- const: Optional[Any] = None
- multipleOf: Optional[float] = Field(default=None, gt=0)
- maximum: Optional[float] = None
- exclusiveMaximum: Optional[float] = None
- minimum: Optional[float] = None
- exclusiveMinimum: Optional[float] = None
- maxLength: Optional[int] = Field(default=None, ge=0)
- minLength: Optional[int] = Field(default=None, ge=0)
- pattern: Optional[str] = None
- maxItems: Optional[int] = Field(default=None, ge=0)
- minItems: Optional[int] = Field(default=None, ge=0)
- uniqueItems: Optional[bool] = None
- maxContains: Optional[int] = Field(default=None, ge=0)
- minContains: Optional[int] = Field(default=None, ge=0)
- maxProperties: Optional[int] = Field(default=None, ge=0)
- minProperties: Optional[int] = Field(default=None, ge=0)
- required: Optional[list[str]] = None
- dependentRequired: Optional[dict[str, set[str]]] = None
+ type: SchemaType | list[SchemaType] | None = None
+ enum: list[Any] | None = None
+ const: Any | None = None
+ multipleOf: float | None = Field(default=None, gt=0)
+ maximum: float | None = None
+ exclusiveMaximum: float | None = None
+ minimum: float | None = None
+ exclusiveMinimum: float | None = None
+ maxLength: int | None = Field(default=None, ge=0)
+ minLength: int | None = Field(default=None, ge=0)
+ pattern: str | None = None
+ maxItems: int | None = Field(default=None, ge=0)
+ minItems: int | None = Field(default=None, ge=0)
+ uniqueItems: bool | None = None
+ maxContains: int | None = Field(default=None, ge=0)
+ minContains: int | None = Field(default=None, ge=0)
+ maxProperties: int | None = Field(default=None, ge=0)
+ minProperties: int | None = Field(default=None, ge=0)
+ required: list[str] | None = None
+ dependentRequired: dict[str, set[str]] | None = None
# Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-vocabularies-for-semantic-c
# Vocabularies for Semantic Content With "format"
- format: Optional[str] = None
+ format: str | None = None
# Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-the-conten
# A Vocabulary for the Contents of String-Encoded Data
- contentEncoding: Optional[str] = None
- contentMediaType: Optional[str] = None
+ contentEncoding: str | None = None
+ contentMediaType: str | None = None
contentSchema: Optional["SchemaOrBool"] = None
# Ref: JSON Schema Validation 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-basic-meta
# A Vocabulary for Basic Meta-Data Annotations
- title: Optional[str] = None
- description: Optional[str] = None
- default: Optional[Any] = None
- deprecated: Optional[bool] = None
- readOnly: Optional[bool] = None
- writeOnly: Optional[bool] = None
- examples: Optional[list[Any]] = None
+ title: str | None = None
+ description: str | None = None
+ default: Any | None = None
+ deprecated: bool | None = None
+ readOnly: bool | None = None
+ writeOnly: bool | None = None
+ examples: list[Any] | None = None
# Ref: OpenAPI 3.1.0: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object
# Schema Object
- discriminator: Optional[Discriminator] = None
- xml: Optional[XML] = None
- externalDocs: Optional[ExternalDocumentation] = None
+ discriminator: Discriminator | None = None
+ xml: XML | None = None
+ externalDocs: ExternalDocumentation | None = None
example: Annotated[
- Optional[Any],
+ Any | None,
typing_deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
# Ref: https://json-schema.org/draft/2020-12/json-schema-core.html#name-json-schema-documents
# A JSON Schema MUST be an object or a boolean.
-SchemaOrBool = Union[Schema, bool]
+SchemaOrBool = Schema | bool
class Example(TypedDict, total=False):
- summary: Optional[str]
- description: Optional[str]
- value: Optional[Any]
- externalValue: Optional[AnyUrl]
+ summary: str | None
+ description: str | None
+ value: Any | None
+ externalValue: AnyUrl | None
__pydantic_config__ = {"extra": "allow"} # type: ignore[misc]
class Encoding(BaseModelWithConfig):
- contentType: Optional[str] = None
- headers: Optional[dict[str, Union["Header", Reference]]] = None
- style: Optional[str] = None
- explode: Optional[bool] = None
- allowReserved: Optional[bool] = None
+ contentType: str | None = None
+ headers: dict[str, Union["Header", Reference]] | None = None
+ style: str | None = None
+ explode: bool | None = None
+ allowReserved: bool | None = None
class MediaType(BaseModelWithConfig):
- schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema")
- example: Optional[Any] = None
- examples: Optional[dict[str, Union[Example, Reference]]] = None
- encoding: Optional[dict[str, Encoding]] = None
+ schema_: Schema | Reference | None = Field(default=None, alias="schema")
+ example: Any | None = None
+ examples: dict[str, Example | Reference] | None = None
+ encoding: dict[str, Encoding] | None = None
class ParameterBase(BaseModelWithConfig):
- description: Optional[str] = None
- required: Optional[bool] = None
- deprecated: Optional[bool] = None
+ description: str | None = None
+ required: bool | None = None
+ deprecated: bool | None = None
# Serialization rules for simple scenarios
- style: Optional[str] = None
- explode: Optional[bool] = None
- allowReserved: Optional[bool] = None
- schema_: Optional[Union[Schema, Reference]] = Field(default=None, alias="schema")
- example: Optional[Any] = None
- examples: Optional[dict[str, Union[Example, Reference]]] = None
+ style: str | None = None
+ explode: bool | None = None
+ allowReserved: bool | None = None
+ schema_: Schema | Reference | None = Field(default=None, alias="schema")
+ example: Any | None = None
+ examples: dict[str, Example | Reference] | None = None
# Serialization rules for more complex scenarios
- content: Optional[dict[str, MediaType]] = None
+ content: dict[str, MediaType] | None = None
class Parameter(ParameterBase):
class RequestBody(BaseModelWithConfig):
- description: Optional[str] = None
+ description: str | None = None
content: dict[str, MediaType]
- required: Optional[bool] = None
+ required: bool | None = None
class Link(BaseModelWithConfig):
- operationRef: Optional[str] = None
- operationId: Optional[str] = None
- parameters: Optional[dict[str, Union[Any, str]]] = None
- requestBody: Optional[Union[Any, str]] = None
- description: Optional[str] = None
- server: Optional[Server] = None
+ operationRef: str | None = None
+ operationId: str | None = None
+ parameters: dict[str, Any | str] | None = None
+ requestBody: Any | str | None = None
+ description: str | None = None
+ server: Server | None = None
class Response(BaseModelWithConfig):
description: str
- headers: Optional[dict[str, Union[Header, Reference]]] = None
- content: Optional[dict[str, MediaType]] = None
- links: Optional[dict[str, Union[Link, Reference]]] = None
+ headers: dict[str, Header | Reference] | None = None
+ content: dict[str, MediaType] | None = None
+ links: dict[str, Link | Reference] | None = None
class Operation(BaseModelWithConfig):
- tags: Optional[list[str]] = None
- summary: Optional[str] = None
- description: Optional[str] = None
- externalDocs: Optional[ExternalDocumentation] = None
- operationId: Optional[str] = None
- parameters: Optional[list[Union[Parameter, Reference]]] = None
- requestBody: Optional[Union[RequestBody, Reference]] = None
+ tags: list[str] | None = None
+ summary: str | None = None
+ description: str | None = None
+ externalDocs: ExternalDocumentation | None = None
+ operationId: str | None = None
+ parameters: list[Parameter | Reference] | None = None
+ requestBody: RequestBody | Reference | None = None
# Using Any for Specification Extensions
- responses: Optional[dict[str, Union[Response, Any]]] = None
- callbacks: Optional[dict[str, Union[dict[str, "PathItem"], Reference]]] = None
- deprecated: Optional[bool] = None
- security: Optional[list[dict[str, list[str]]]] = None
- servers: Optional[list[Server]] = None
+ responses: dict[str, Response | Any] | None = None
+ callbacks: dict[str, dict[str, "PathItem"] | Reference] | None = None
+ deprecated: bool | None = None
+ security: list[dict[str, list[str]]] | None = None
+ servers: list[Server] | None = None
class PathItem(BaseModelWithConfig):
- ref: Optional[str] = Field(default=None, alias="$ref")
- summary: Optional[str] = None
- description: Optional[str] = None
- get: Optional[Operation] = None
- put: Optional[Operation] = None
- post: Optional[Operation] = None
- delete: Optional[Operation] = None
- options: Optional[Operation] = None
- head: Optional[Operation] = None
- patch: Optional[Operation] = None
- trace: Optional[Operation] = None
- servers: Optional[list[Server]] = None
- parameters: Optional[list[Union[Parameter, Reference]]] = None
+ ref: str | None = Field(default=None, alias="$ref")
+ summary: str | None = None
+ description: str | None = None
+ get: Operation | None = None
+ put: Operation | None = None
+ post: Operation | None = None
+ delete: Operation | None = None
+ options: Operation | None = None
+ head: Operation | None = None
+ patch: Operation | None = None
+ trace: Operation | None = None
+ servers: list[Server] | None = None
+ parameters: list[Parameter | Reference] | None = None
class SecuritySchemeType(Enum):
class SecurityBase(BaseModelWithConfig):
type_: SecuritySchemeType = Field(alias="type")
- description: Optional[str] = None
+ description: str | None = None
class APIKeyIn(Enum):
class HTTPBearer(HTTPBase):
scheme: Literal["bearer"] = "bearer"
- bearerFormat: Optional[str] = None
+ bearerFormat: str | None = None
class OAuthFlow(BaseModelWithConfig):
- refreshUrl: Optional[str] = None
+ refreshUrl: str | None = None
scopes: dict[str, str] = {}
class OAuthFlows(BaseModelWithConfig):
- implicit: Optional[OAuthFlowImplicit] = None
- password: Optional[OAuthFlowPassword] = None
- clientCredentials: Optional[OAuthFlowClientCredentials] = None
- authorizationCode: Optional[OAuthFlowAuthorizationCode] = None
+ implicit: OAuthFlowImplicit | None = None
+ password: OAuthFlowPassword | None = None
+ clientCredentials: OAuthFlowClientCredentials | None = None
+ authorizationCode: OAuthFlowAuthorizationCode | None = None
class OAuth2(SecurityBase):
openIdConnectUrl: str
-SecurityScheme = Union[APIKey, HTTPBase, OAuth2, OpenIdConnect, HTTPBearer]
+SecurityScheme = APIKey | HTTPBase | OAuth2 | OpenIdConnect | HTTPBearer
class Components(BaseModelWithConfig):
- schemas: Optional[dict[str, Union[Schema, Reference]]] = None
- responses: Optional[dict[str, Union[Response, Reference]]] = None
- parameters: Optional[dict[str, Union[Parameter, Reference]]] = None
- examples: Optional[dict[str, Union[Example, Reference]]] = None
- requestBodies: Optional[dict[str, Union[RequestBody, Reference]]] = None
- headers: Optional[dict[str, Union[Header, Reference]]] = None
- securitySchemes: Optional[dict[str, Union[SecurityScheme, Reference]]] = None
- links: Optional[dict[str, Union[Link, Reference]]] = None
+ schemas: dict[str, Schema | Reference] | None = None
+ responses: dict[str, Response | Reference] | None = None
+ parameters: dict[str, Parameter | Reference] | None = None
+ examples: dict[str, Example | Reference] | None = None
+ requestBodies: dict[str, RequestBody | Reference] | None = None
+ headers: dict[str, Header | Reference] | None = None
+ securitySchemes: dict[str, SecurityScheme | Reference] | None = None
+ links: dict[str, Link | Reference] | None = None
# Using Any for Specification Extensions
- callbacks: Optional[dict[str, Union[dict[str, PathItem], Reference, Any]]] = None
- pathItems: Optional[dict[str, Union[PathItem, Reference]]] = None
+ callbacks: dict[str, dict[str, PathItem] | Reference | Any] | None = None
+ pathItems: dict[str, PathItem | Reference] | None = None
class Tag(BaseModelWithConfig):
name: str
- description: Optional[str] = None
- externalDocs: Optional[ExternalDocumentation] = None
+ description: str | None = None
+ externalDocs: ExternalDocumentation | None = None
class OpenAPI(BaseModelWithConfig):
openapi: str
info: Info
- jsonSchemaDialect: Optional[str] = None
- servers: Optional[list[Server]] = None
+ jsonSchemaDialect: str | None = None
+ servers: list[Server] | None = None
# Using Any for Specification Extensions
- paths: Optional[dict[str, Union[PathItem, Any]]] = None
- webhooks: Optional[dict[str, Union[PathItem, Reference]]] = None
- components: Optional[Components] = None
- security: Optional[list[dict[str, list[str]]]] = None
- tags: Optional[list[Tag]] = None
- externalDocs: Optional[ExternalDocumentation] = None
+ paths: dict[str, PathItem | Any] | None = None
+ webhooks: dict[str, PathItem | Reference] | None = None
+ components: Components | None = None
+ security: list[dict[str, list[str]]] | None = None
+ tags: list[Tag] | None = None
+ externalDocs: ExternalDocumentation | None = None
Schema.model_rebuild()
import inspect
import warnings
from collections.abc import Sequence
-from typing import Any, Optional, Union, cast
+from typing import Any, Literal, cast
from fastapi import routing
from fastapi._compat import (
from pydantic import BaseModel
from starlette.responses import JSONResponse
from starlette.routing import BaseRoute
-from typing_extensions import Literal
validation_error_definition = {
"title": "ValidationError",
def get_openapi_operation_request_body(
*,
- body_field: Optional[ModelField],
+ body_field: ModelField | None,
model_name_map: ModelNameMap,
field_mapping: dict[
tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any]
],
separate_input_output_schemas: bool = True,
-) -> Optional[dict[str, Any]]:
+) -> dict[str, Any] | None:
if not body_field:
return None
assert isinstance(body_field, ModelField)
else:
current_response_class = route.response_class
assert current_response_class, "A response class is needed to generate OpenAPI"
- route_response_media_type: Optional[str] = current_response_class.media_type
+ route_response_media_type: str | None = current_response_class.media_type
if route.include_in_schema:
for method in route.methods:
operation = get_openapi_operation_metadata(
"An additional response must be a dict"
)
field = route.response_fields.get(additional_status_code)
- additional_field_schema: Optional[dict[str, Any]] = None
+ additional_field_schema: dict[str, Any] | None = None
if field:
additional_field_schema = get_schema_from_model_field(
field=field,
.setdefault("schema", {})
)
deep_dict_update(additional_schema, additional_field_schema)
- status_text: Optional[str] = status_code_ranges.get(
+ status_text: str | None = status_code_ranges.get(
str(additional_status_code).upper()
) or http.client.responses.get(int(additional_status_code))
description = (
title: str,
version: str,
openapi_version: str = "3.1.0",
- summary: Optional[str] = None,
- description: Optional[str] = None,
+ summary: str | None = None,
+ description: str | None = None,
routes: Sequence[BaseRoute],
- webhooks: Optional[Sequence[BaseRoute]] = None,
- tags: Optional[list[dict[str, Any]]] = None,
- servers: Optional[list[dict[str, Union[str, Any]]]] = None,
- terms_of_service: Optional[str] = None,
- contact: Optional[dict[str, Union[str, Any]]] = None,
- license_info: Optional[dict[str, Union[str, Any]]] = None,
+ webhooks: Sequence[BaseRoute] | None = None,
+ tags: list[dict[str, Any]] | None = None,
+ servers: list[dict[str, str | Any]] | None = None,
+ terms_of_service: str | None = None,
+ contact: dict[str, str | Any] | None = None,
+ license_info: dict[str, str | Any] | None = None,
separate_input_output_schemas: bool = True,
- external_docs: Optional[dict[str, Any]] = None,
+ external_docs: dict[str, Any] | None = None,
) -> dict[str, Any]:
info: dict[str, Any] = {"title": title, "version": version}
if summary:
-from collections.abc import Sequence
-from typing import Annotated, Any, Callable, Optional, Union
+from collections.abc import Callable, Sequence
+from typing import Annotated, Any, Literal
from annotated_doc import Doc
from fastapi import params
from fastapi._compat import Undefined
from fastapi.openapi.models import Example
from pydantic import AliasChoices, AliasPath
-from typing_extensions import Literal, deprecated
+from typing_extensions import deprecated
_Unset: Any = Undefined
] = ...,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = _Unset,
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = None,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
] = Undefined,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = _Unset,
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = None,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
] = Undefined,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = _Unset,
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = True,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
] = Undefined,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = _Unset,
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = None,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
] = Undefined,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = _Unset,
embed: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
When `embed` is `True`, the parameter will be expected in a JSON body as a
),
] = "application/json",
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = None,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
] = Undefined,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = "application/x-www-form-urlencoded",
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = None,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
] = Undefined,
*,
default_factory: Annotated[
- Union[Callable[[], Any], None],
+ Callable[[], Any] | None,
Doc(
"""
A callable to generate the default value.
),
] = "multipart/form-data",
alias: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
An alternative name for the parameter field.
),
] = None,
alias_priority: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Priority of the alias. This affects whether an alias generator is used.
),
] = _Unset,
validation_alias: Annotated[
- Union[str, AliasPath, AliasChoices, None],
+ str | AliasPath | AliasChoices | None,
Doc(
"""
'Whitelist' validation step. The parameter field will be the single one
),
] = None,
serialization_alias: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
'Blacklist' validation step. The vanilla parameter field will be the
),
] = None,
title: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable title.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Human-readable description.
),
] = None,
gt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than. If set, value must be greater than this. Only applicable to
),
] = None,
ge: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Greater than or equal. If set, value must be greater than or equal to
),
] = None,
lt: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than. If set, value must be less than this. Only applicable to numbers.
),
] = None,
le: Annotated[
- Optional[float],
+ float | None,
Doc(
"""
Less than or equal. If set, value must be less than or equal to this.
),
] = None,
min_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Minimum length for strings.
),
] = None,
max_length: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
Maximum length for strings.
),
] = None,
pattern: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
regex: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
RegEx pattern for strings.
),
] = None,
discriminator: Annotated[
- Union[str, None],
+ str | None,
Doc(
"""
Parameter field name for discriminating the type in a tagged union.
),
] = None,
strict: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
If `True`, strict validation is applied to the field.
),
] = _Unset,
multiple_of: Annotated[
- Union[float, None],
+ float | None,
Doc(
"""
Value must be a multiple of this. Only applicable to numbers.
),
] = _Unset,
allow_inf_nan: Annotated[
- Union[bool, None],
+ bool | None,
Doc(
"""
Allow `inf`, `-inf`, `nan`. Only applicable to numbers.
),
] = _Unset,
max_digits: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of allow digits for strings.
),
] = _Unset,
decimal_places: Annotated[
- Union[int, None],
+ int | None,
Doc(
"""
Maximum number of decimal places allowed for numbers.
),
] = _Unset,
examples: Annotated[
- Optional[list[Any]],
+ list[Any] | None,
Doc(
"""
Example values for this field.
),
] = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
openapi_examples: Annotated[
- Optional[dict[str, Example]],
+ dict[str, Example] | None,
Doc(
"""
OpenAPI-specific examples.
),
] = None,
deprecated: Annotated[
- Union[deprecated, str, bool, None],
+ deprecated | str | bool | None,
Doc(
"""
Mark this parameter field as deprecated.
),
] = True,
json_schema_extra: Annotated[
- Union[dict[str, Any], None],
+ dict[str, Any] | None,
Doc(
"""
Any additional JSON schema data.
def Depends( # noqa: N802
dependency: Annotated[
- Optional[Callable[..., Any]],
+ Callable[..., Any] | None,
Doc(
"""
A "dependable" callable (like a function).
),
] = True,
scope: Annotated[
- Union[Literal["function", "request"], None],
+ Literal["function", "request"] | None,
Doc(
"""
Mainly for dependencies with `yield`, define when the dependency function
def Security( # noqa: N802
dependency: Annotated[
- Optional[Callable[..., Any]],
+ Callable[..., Any] | None,
Doc(
"""
A "dependable" callable (like a function).
] = None,
*,
scopes: Annotated[
- Optional[Sequence[str]],
+ Sequence[str] | None,
Doc(
"""
OAuth2 scopes required for the *path operation* that uses this Security
import warnings
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from dataclasses import dataclass
from enum import Enum
-from typing import Annotated, Any, Callable, Optional, Union
+from typing import Annotated, Any, Literal
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.openapi.models import Example
from pydantic import AliasChoices, AliasPath
from pydantic.fields import FieldInfo
-from typing_extensions import Literal, deprecated
+from typing_extensions import deprecated
from ._compat import (
Undefined,
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
if example is not _Unset:
self,
default: Any = ...,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
assert default is ..., "Path parameters cannot have a default value"
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
super().__init__(
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | AliasChoices | None = None,
+ serialization_alias: str | None = None,
convert_underscores: bool = True,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
self.convert_underscores = convert_underscores
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
super().__init__(
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
- embed: Union[bool, None] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
+ embed: bool | None = None,
media_type: str = "application/json",
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
self.embed = embed
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
media_type: str = "application/x-www-form-urlencoded",
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
super().__init__(
self,
default: Any = Undefined,
*,
- default_factory: Union[Callable[[], Any], None] = _Unset,
- annotation: Optional[Any] = None,
+ default_factory: Callable[[], Any] | None = _Unset,
+ annotation: Any | None = None,
media_type: str = "multipart/form-data",
- alias: Optional[str] = None,
- alias_priority: Union[int, None] = _Unset,
- validation_alias: Union[str, AliasPath, AliasChoices, None] = None,
- serialization_alias: Union[str, None] = None,
- title: Optional[str] = None,
- description: Optional[str] = None,
- gt: Optional[float] = None,
- ge: Optional[float] = None,
- lt: Optional[float] = None,
- le: Optional[float] = None,
- min_length: Optional[int] = None,
- max_length: Optional[int] = None,
- pattern: Optional[str] = None,
+ alias: str | None = None,
+ alias_priority: int | None = _Unset,
+ validation_alias: str | AliasPath | 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[
- Optional[str],
+ str | None,
deprecated(
"Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead."
),
] = None,
- discriminator: Union[str, None] = None,
- strict: Union[bool, None] = _Unset,
- multiple_of: Union[float, None] = _Unset,
- allow_inf_nan: Union[bool, None] = _Unset,
- max_digits: Union[int, None] = _Unset,
- decimal_places: Union[int, None] = _Unset,
- examples: Optional[list[Any]] = None,
+ discriminator: str | None = None,
+ strict: bool | None = _Unset,
+ multiple_of: float | None = _Unset,
+ allow_inf_nan: bool | None = _Unset,
+ max_digits: int | None = _Unset,
+ decimal_places: int | None = _Unset,
+ examples: list[Any] | None = None,
example: Annotated[
- Optional[Any],
+ Any | None,
deprecated(
"Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, "
"although still supported. Use examples instead."
),
] = _Unset,
- openapi_examples: Optional[dict[str, Example]] = None,
- deprecated: Union[deprecated, str, bool, None] = None,
+ openapi_examples: dict[str, Example] | None = None,
+ deprecated: deprecated | str | bool | None = None,
include_in_schema: bool = True,
- json_schema_extra: Union[dict[str, Any], None] = None,
+ json_schema_extra: dict[str, Any] | None = None,
**extra: Any,
):
super().__init__(
@dataclass(frozen=True)
class Depends:
- dependency: Optional[Callable[..., Any]] = None
+ dependency: Callable[..., Any] | None = None
use_cache: bool = True
- scope: Union[Literal["function", "request"], None] = None
+ scope: Literal["function", "request"] | None = None
@dataclass(frozen=True)
class Security(Depends):
- scopes: Optional[Sequence[str]] = None
+ scopes: Sequence[str] | None = None
from collections.abc import (
AsyncIterator,
Awaitable,
+ Callable,
Collection,
Coroutine,
Generator,
from typing import (
Annotated,
Any,
- Callable,
- Optional,
TypeVar,
- Union,
)
from annotated_doc import Doc
# Copy of starlette.routing.request_response modified to include the
# dependencies' AsyncExitStack
def request_response(
- func: Callable[[Request], Union[Awaitable[Response], Response]],
+ func: Callable[[Request], Awaitable[Response] | Response],
) -> ASGIApp:
"""
Takes a function or coroutine `func(request) -> response`,
async def __aexit__(
self,
- exc_type: Optional[type[BaseException]],
- exc_value: Optional[BaseException],
- traceback: Optional[types.TracebackType],
- ) -> Optional[bool]:
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: types.TracebackType | None,
+ ) -> bool | None:
return self._cm.__exit__(exc_type, exc_value, traceback)
@asynccontextmanager
async def merged_lifespan(
app: AppType,
- ) -> AsyncIterator[Optional[Mapping[str, Any]]]:
+ ) -> AsyncIterator[Mapping[str, Any] | None]:
async with original_context(app) as maybe_original_state:
async with nested_context(app) as maybe_nested_state:
if maybe_nested_state is None and maybe_original_state is None:
async def serialize_response(
*,
- field: Optional[ModelField] = None,
+ field: ModelField | None = None,
response_content: Any,
- include: Optional[IncEx] = None,
- exclude: Optional[IncEx] = None,
+ include: IncEx | None = None,
+ exclude: IncEx | None = None,
by_alias: bool = True,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
is_coroutine: bool = True,
- endpoint_ctx: Optional[EndpointContext] = None,
+ endpoint_ctx: EndpointContext | None = None,
) -> Any:
if field:
if is_coroutine:
def get_request_handler(
dependant: Dependant,
- body_field: Optional[ModelField] = None,
- status_code: Optional[int] = None,
- response_class: Union[type[Response], DefaultPlaceholder] = Default(JSONResponse),
- response_field: Optional[ModelField] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
+ body_field: ModelField | None = None,
+ status_code: int | None = None,
+ response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
+ response_field: ModelField | None = None,
+ response_model_include: IncEx | None = None,
+ response_model_exclude: IncEx | None = 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: Optional[Any] = None,
+ dependency_overrides_provider: Any | None = None,
embed_body_fields: bool = False,
) -> Callable[[Request], Coroutine[Any, Any, Response]]:
assert dependant.call is not None, "dependant.call must be a function"
actual_response_class = response_class
async def app(request: Request) -> Response:
- response: Union[Response, None] = None
+ response: Response | None = None
file_stack = request.scope.get("fastapi_middleware_astack")
assert isinstance(file_stack, AsyncExitStack), (
"fastapi_middleware_astack not found in request scope"
def get_websocket_app(
dependant: Dependant,
- dependency_overrides_provider: Optional[Any] = None,
+ dependency_overrides_provider: Any | None = None,
embed_body_fields: bool = False,
) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:
async def app(websocket: WebSocket) -> None:
path: str,
endpoint: Callable[..., Any],
*,
- name: Optional[str] = None,
- dependencies: Optional[Sequence[params.Depends]] = None,
- dependency_overrides_provider: Optional[Any] = None,
+ name: str | None = None,
+ dependencies: Sequence[params.Depends] | None = None,
+ dependency_overrides_provider: Any | None = None,
) -> None:
self.path = path
self.endpoint = endpoint
endpoint: Callable[..., Any],
*,
response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[list[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[params.Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
+ status_code: int | None = None,
+ tags: list[str | Enum] | None = None,
+ dependencies: Sequence[params.Depends] | None = None,
+ summary: str | None = None,
+ description: str | None = None,
response_description: str = "Successful Response",
- responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- name: Optional[str] = None,
- methods: Optional[Union[set[str], list[str]]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
+ responses: dict[int | str, dict[str, 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: IncEx | None = None,
+ response_model_exclude: IncEx | None = 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: Union[type[Response], DefaultPlaceholder] = Default(
- JSONResponse
- ),
- dependency_overrides_provider: Optional[Any] = None,
- callbacks: Optional[list[BaseRoute]] = None,
- openapi_extra: Optional[dict[str, Any]] = None,
- generate_unique_id_function: Union[
- Callable[["APIRoute"], str], DefaultPlaceholder
- ] = Default(generate_unique_id),
+ response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
+ dependency_overrides_provider: Any | None = None,
+ callbacks: list[BaseRoute] | None = None,
+ openapi_extra: dict[str, Any] | None = None,
+ generate_unique_id_function: Callable[["APIRoute"], str]
+ | DefaultPlaceholder = Default(generate_unique_id),
) -> None:
self.path = path
self.endpoint = endpoint
)
response_fields[additional_status_code] = response_field
if response_fields:
- self.response_fields: dict[Union[int, str], ModelField] = response_fields
+ self.response_fields: dict[int | str, ModelField] = response_fields
else:
self.response_fields = {}
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to all the *path operations* in this
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to all the
),
] = Default(JSONResponse),
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses to be shown in OpenAPI.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
OpenAPI callbacks that should apply to all *path operations* in this
),
] = None,
routes: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
**Note**: you probably shouldn't use this parameter, it is inherited
),
] = True,
default: Annotated[
- Optional[ASGIApp],
+ ASGIApp | None,
Doc(
"""
Default function handler for this router. Used to handle
),
] = None,
dependency_overrides_provider: Annotated[
- Optional[Any],
+ Any | None,
Doc(
"""
Only used internally by FastAPI to handle dependency overrides.
),
] = APIRoute,
on_startup: Annotated[
- Optional[Sequence[Callable[[], Any]]],
+ Sequence[Callable[[], Any]] | None,
Doc(
"""
A list of startup event handler functions.
),
] = None,
on_shutdown: Annotated[
- Optional[Sequence[Callable[[], Any]]],
+ Sequence[Callable[[], Any]] | None,
Doc(
"""
A list of shutdown event handler functions.
# the generic to Lifespan[AppType] is the type of the top level application
# which the router cannot know statically, so we use typing.Any
lifespan: Annotated[
- Optional[Lifespan[Any]],
+ Lifespan[Any] | None,
Doc(
"""
A `Lifespan` context manager handler. This replaces `startup` and
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark all *path operations* in this router as deprecated.
)
self.prefix = prefix
- self.tags: list[Union[str, Enum]] = tags or []
+ self.tags: list[str | Enum] = tags or []
self.dependencies = list(dependencies or [])
self.deprecated = deprecated
self.include_in_schema = include_in_schema
def route(
self,
path: str,
- methods: Optional[Collection[str]] = None,
- name: Optional[str] = None,
+ methods: Collection[str] | None = None,
+ name: str | None = None,
include_in_schema: bool = True,
) -> Callable[[DecoratedCallable], DecoratedCallable]:
def decorator(func: DecoratedCallable) -> DecoratedCallable:
endpoint: Callable[..., Any],
*,
response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[list[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[params.Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
+ status_code: int | None = None,
+ tags: list[str | Enum] | None = None,
+ dependencies: Sequence[params.Depends] | None = None,
+ summary: str | None = None,
+ description: str | None = None,
response_description: str = "Successful Response",
- responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- methods: Optional[Union[set[str], list[str]]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
+ responses: dict[int | str, dict[str, Any]] | None = None,
+ deprecated: bool | None = None,
+ methods: set[str] | list[str] | None = None,
+ operation_id: str | None = None,
+ response_model_include: IncEx | None = None,
+ response_model_exclude: IncEx | None = 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: Union[type[Response], DefaultPlaceholder] = Default(
- JSONResponse
- ),
- name: Optional[str] = None,
- route_class_override: Optional[type[APIRoute]] = None,
- callbacks: Optional[list[BaseRoute]] = None,
- openapi_extra: Optional[dict[str, Any]] = None,
- generate_unique_id_function: Union[
- Callable[[APIRoute], str], DefaultPlaceholder
- ] = Default(generate_unique_id),
+ response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse),
+ name: str | None = None,
+ route_class_override: type[APIRoute] | None = None,
+ callbacks: list[BaseRoute] | None = None,
+ openapi_extra: dict[str, Any] | None = None,
+ generate_unique_id_function: Callable[[APIRoute], str]
+ | DefaultPlaceholder = Default(generate_unique_id),
) -> None:
route_class = route_class_override or self.route_class
responses = responses or {}
path: str,
*,
response_model: Any = Default(None),
- status_code: Optional[int] = None,
- tags: Optional[list[Union[str, Enum]]] = None,
- dependencies: Optional[Sequence[params.Depends]] = None,
- summary: Optional[str] = None,
- description: Optional[str] = None,
+ status_code: int | None = None,
+ tags: list[str | Enum] | None = None,
+ dependencies: Sequence[params.Depends] | None = None,
+ summary: str | None = None,
+ description: str | None = None,
response_description: str = "Successful Response",
- responses: Optional[dict[Union[int, str], dict[str, Any]]] = None,
- deprecated: Optional[bool] = None,
- methods: Optional[list[str]] = None,
- operation_id: Optional[str] = None,
- response_model_include: Optional[IncEx] = None,
- response_model_exclude: Optional[IncEx] = None,
+ responses: dict[int | str, dict[str, Any]] | None = None,
+ deprecated: bool | None = None,
+ methods: list[str] | None = None,
+ operation_id: str | None = None,
+ response_model_include: IncEx | None = None,
+ response_model_exclude: IncEx | None = 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[Response] = Default(JSONResponse),
- name: Optional[str] = None,
- callbacks: Optional[list[BaseRoute]] = None,
- openapi_extra: Optional[dict[str, Any]] = None,
+ name: str | None = None,
+ callbacks: list[BaseRoute] | None = None,
+ openapi_extra: dict[str, Any] | None = None,
generate_unique_id_function: Callable[[APIRoute], str] = Default(
generate_unique_id
),
self,
path: str,
endpoint: Callable[..., Any],
- name: Optional[str] = None,
+ name: str | None = None,
*,
- dependencies: Optional[Sequence[params.Depends]] = None,
+ dependencies: Sequence[params.Depends] | None = None,
) -> None:
current_dependencies = self.dependencies.copy()
if dependencies:
),
],
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A name for the WebSocket. Only used internally.
] = None,
*,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be used for this
return decorator
def websocket_route(
- self, path: str, name: Union[str, None] = None
+ self, path: str, name: str | None = None
) -> Callable[[DecoratedCallable], DecoratedCallable]:
def decorator(func: DecoratedCallable) -> DecoratedCallable:
self.add_websocket_route(path, func, name=name)
*,
prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "",
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to all the *path operations* in this
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to all the
),
] = Default(JSONResponse),
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses to be shown in OpenAPI.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
OpenAPI callbacks that should apply to all *path operations* in this
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark all *path operations* in this router as deprecated.
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
),
] = Default(None),
status_code: Annotated[
- Optional[int],
+ int | None,
Doc(
"""
The default status code to be used for the response.
),
] = None,
tags: Annotated[
- Optional[list[Union[str, Enum]]],
+ list[str | Enum] | None,
Doc(
"""
A list of tags to be applied to the *path operation*.
),
] = None,
dependencies: Annotated[
- Optional[Sequence[params.Depends]],
+ Sequence[params.Depends] | None,
Doc(
"""
A list of dependencies (using `Depends()`) to be applied to the
),
] = None,
summary: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A summary for the *path operation*.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
A description for the *path operation*.
),
] = "Successful Response",
responses: Annotated[
- Optional[dict[Union[int, str], dict[str, Any]]],
+ dict[int | str, dict[str, Any]] | None,
Doc(
"""
Additional responses that could be returned by this *path operation*.
),
] = None,
deprecated: Annotated[
- Optional[bool],
+ bool | None,
Doc(
"""
Mark this *path operation* as deprecated.
),
] = None,
operation_id: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Custom operation ID to be used by this *path operation*.
),
] = None,
response_model_include: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to include only certain fields in the
),
] = None,
response_model_exclude: Annotated[
- Optional[IncEx],
+ IncEx | None,
Doc(
"""
Configuration passed to Pydantic to exclude certain fields in the
),
] = Default(JSONResponse),
name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Name for this *path operation*. Only used internally.
),
] = None,
callbacks: Annotated[
- Optional[list[BaseRoute]],
+ list[BaseRoute] | None,
Doc(
"""
List of *path operations* that will be used as OpenAPI callbacks.
),
] = None,
openapi_extra: Annotated[
- Optional[dict[str, Any]],
+ dict[str, Any] | None,
Doc(
"""
Extra metadata to be included in the OpenAPI schema for this *path
-from typing import Annotated, Optional, Union
+from typing import Annotated
from annotated_doc import Doc
from fastapi.openapi.models import APIKey, APIKeyIn
self,
location: APIKeyIn,
name: str,
- description: Union[str, None],
- scheme_name: Union[str, None],
+ description: str | None,
+ scheme_name: str | None,
auto_error: bool,
):
self.auto_error = auto_error
headers={"WWW-Authenticate": "APIKey"},
)
- def check_api_key(self, api_key: Optional[str]) -> Optional[str]:
+ def check_api_key(self, api_key: str | None) -> str | None:
if not api_key:
if self.auto_error:
raise self.make_not_authenticated_error()
Doc("Query parameter name."),
],
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
auto_error=auto_error,
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
api_key = request.query_params.get(self.model.name)
return self.check_api_key(api_key)
*,
name: Annotated[str, Doc("Header name.")],
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
auto_error=auto_error,
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
api_key = request.headers.get(self.model.name)
return self.check_api_key(api_key)
*,
name: Annotated[str, Doc("Cookie name.")],
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
auto_error=auto_error,
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
api_key = request.cookies.get(self.model.name)
return self.check_api_key(api_key)
import binascii
from base64 import b64decode
-from typing import Annotated, Optional
+from typing import Annotated
from annotated_doc import Doc
from fastapi.exceptions import HTTPException
self,
*,
scheme: str,
- scheme_name: Optional[str] = None,
- description: Optional[str] = None,
+ scheme_name: str | None = None,
+ description: str | None = None,
auto_error: bool = True,
):
self.model: HTTPBaseModel = HTTPBaseModel(
headers=self.make_authenticate_headers(),
)
- async def __call__(
- self, request: Request
- ) -> Optional[HTTPAuthorizationCredentials]:
+ async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:
authorization = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
self,
*,
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
realm: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
HTTP Basic authentication realm.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
async def __call__( # type: ignore
self, request: Request
- ) -> Optional[HTTPBasicCredentials]:
+ ) -> HTTPBasicCredentials | None:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "basic":
def __init__(
self,
*,
- bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None,
+ bearerFormat: Annotated[str | None, Doc("Bearer token format.")] = None,
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
self.scheme_name = scheme_name or self.__class__.__name__
self.auto_error = auto_error
- async def __call__(
- self, request: Request
- ) -> Optional[HTTPAuthorizationCredentials]:
+ async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:
authorization = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
self,
*,
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
self.scheme_name = scheme_name or self.__class__.__name__
self.auto_error = auto_error
- async def __call__(
- self, request: Request
- ) -> Optional[HTTPAuthorizationCredentials]:
+ async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None:
authorization = request.headers.get("Authorization")
scheme, credentials = get_authorization_scheme_param(authorization)
if not (authorization and scheme and credentials):
-from typing import Annotated, Any, Optional, Union, cast
+from typing import Annotated, Any, cast
from annotated_doc import Doc
from fastapi.exceptions import HTTPException
self,
*,
grant_type: Annotated[
- Union[str, None],
+ str | None,
Form(pattern="^password$"),
Doc(
"""
),
] = "",
client_id: Annotated[
- Union[str, None],
+ str | None,
Form(),
Doc(
"""
),
] = None,
client_secret: Annotated[
- Union[str, None],
+ str | None,
Form(json_schema_extra={"format": "password"}),
Doc(
"""
),
] = "",
client_id: Annotated[
- Union[str, None],
+ str | None,
Form(),
Doc(
"""
),
] = None,
client_secret: Annotated[
- Union[str, None],
+ str | None,
Form(),
Doc(
"""
self,
*,
flows: Annotated[
- Union[OAuthFlowsModel, dict[str, dict[str, Any]]],
+ OAuthFlowsModel | dict[str, dict[str, Any]],
Doc(
"""
The dictionary of OAuth2 flows.
),
] = OAuthFlowsModel(),
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
headers={"WWW-Authenticate": "Bearer"},
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
authorization = request.headers.get("Authorization")
if not authorization:
if self.auto_error:
),
],
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
scopes: Annotated[
- Optional[dict[str, str]],
+ dict[str, str] | None,
Doc(
"""
The OAuth2 scopes that would be required by the *path operations* that
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
),
] = True,
refreshUrl: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The URL to refresh the token and obtain a new one.
auto_error=auto_error,
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
),
],
refreshUrl: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
The URL to refresh the token and obtain a new one.
),
] = None,
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
scopes: Annotated[
- Optional[dict[str, str]],
+ dict[str, str] | None,
Doc(
"""
The OAuth2 scopes that would be required by the *path operations* that
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
auto_error=auto_error,
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
def __init__(
self,
scopes: Annotated[
- Optional[list[str]],
+ list[str] | None,
Doc(
"""
This will be filled by FastAPI.
-from typing import Annotated, Optional
+from typing import Annotated
from annotated_doc import Doc
from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel
),
],
scheme_name: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme name.
),
] = None,
description: Annotated[
- Optional[str],
+ str | None,
Doc(
"""
Security scheme description.
headers={"WWW-Authenticate": "Bearer"},
)
- async def __call__(self, request: Request) -> Optional[str]:
+ async def __call__(self, request: Request) -> str | None:
authorization = request.headers.get("Authorization")
if not authorization:
if self.auto_error:
-from typing import Optional
-
-
def get_authorization_scheme_param(
- authorization_header_value: Optional[str],
+ authorization_header_value: str | None,
) -> tuple[str, str]:
if not authorization_header_value:
return "", ""
import types
+from collections.abc import Callable
from enum import Enum
-from typing import Any, Callable, Optional, TypeVar, Union
+from typing import Any, TypeVar, Union
from pydantic import BaseModel
from pydantic.main import IncEx as IncEx
DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any])
UnionType = getattr(types, "UnionType", Union)
-ModelNameMap = dict[Union[type[BaseModel], type[Enum]], str]
-DependencyCacheKey = tuple[Optional[Callable[..., Any]], tuple[str, ...], str]
+ModelNameMap = dict[type[BaseModel] | type[Enum], str]
+DependencyCacheKey = tuple[Callable[..., Any] | None, tuple[str, ...], str]
from typing import (
TYPE_CHECKING,
Any,
- Optional,
- Union,
+ Literal,
)
import fastapi
from fastapi.datastructures import DefaultPlaceholder, DefaultType
from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError
from pydantic.fields import FieldInfo
-from typing_extensions import Literal
from ._compat import v2
from .routing import APIRoute
-def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool:
+def is_body_allowed_for_status_code(status_code: int | str | None) -> bool:
if status_code is None:
return True
# Ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#patterned-fields-1
def create_model_field(
name: str,
type_: Any,
- default: Optional[Any] = Undefined,
- field_info: Optional[FieldInfo] = None,
- alias: Optional[str] = None,
+ default: Any | None = Undefined,
+ field_info: FieldInfo | None = None,
+ alias: str | None = None,
mode: Literal["validation", "serialization"] = "validation",
) -> ModelField:
if annotation_is_pydantic_v1(type_):
def get_value_or_default(
- first_item: Union[DefaultPlaceholder, DefaultType],
- *extra_items: Union[DefaultPlaceholder, DefaultType],
-) -> Union[DefaultPlaceholder, DefaultType]:
+ first_item: DefaultPlaceholder | DefaultType,
+ *extra_items: DefaultPlaceholder | DefaultType,
+) -> DefaultPlaceholder | DefaultType:
"""
Pass items or `DefaultPlaceholder`s by descending priority.