repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/templating.py
fastapi/templating.py
from starlette.templating import Jinja2Templates as Jinja2Templates # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/__main__.py
fastapi/__main__.py
from fastapi.cli import main main()
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/param_functions.py
fastapi/param_functions.py
from collections.abc import Sequence from typing import Annotated, Any, Callable, Optional, Union 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 _Unset: Any = Undefined def Path( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = ..., *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ Union[str, AliasPath, AliasChoices, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[list[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], 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]], Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: """ Declare a path parameter for a *path operation*. Read more about it in the [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/). ```python from typing import Annotated from fastapi import FastAPI, Path app = FastAPI() @app.get("/items/{item_id}") async def read_items( item_id: Annotated[int, Path(title="The ID of the item to get")], ): return {"item_id": item_id} ``` """ return params.Path( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Query( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ Union[str, AliasPath, AliasChoices, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[list[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], 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]], Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Query( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Header( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ Union[str, AliasPath, AliasChoices, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, convert_underscores: Annotated[ bool, Doc( """ Automatically convert underscores to hyphens in the parameter field name. Read more about it in the [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) """ ), ] = True, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[list[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], 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]], Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Header( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, convert_underscores=convert_underscores, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Cookie( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Union[Callable[[], Any], None], Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ Optional[str], Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ Union[int, None], Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ Union[str, AliasPath, AliasChoices, None], Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ Union[str, None], Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ Optional[str], Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ Optional[float], Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ Optional[float], Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ Optional[float], Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ Optional[float], Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ Optional[int], Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ Optional[int], Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ Optional[str], Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ Union[str, None], Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ Union[bool, None], Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ Union[float, None], Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ Union[bool, None], Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ Union[int, None], Doc( """ Maximum number of allow digits for strings. """ ), ] = _Unset, decimal_places: Annotated[ Union[int, None], Doc( """ Maximum number of decimal places allowed for numbers. """ ), ] = _Unset, examples: Annotated[ Optional[list[Any]], Doc( """ Example values for this field. """ ), ] = None, example: Annotated[ Optional[Any], 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]], Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ Union[deprecated, str, bool, None], Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ Union[dict[str, Any], None], Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Cookie( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias,
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/testclient.py
fastapi/testclient.py
from starlette.testclient import TestClient as TestClient # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/background.py
fastapi/background.py
from typing import Annotated, Any, Callable from annotated_doc import Doc from starlette.background import BackgroundTasks as StarletteBackgroundTasks from typing_extensions import ParamSpec P = ParamSpec("P") class BackgroundTasks(StarletteBackgroundTasks): """ A collection of background tasks that will be called after a response has been sent to the client. Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). ## Example ```python from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_notification, email, message="some notification") return {"message": "Notification sent in the background"} ``` """ def add_task( self, func: Annotated[ Callable[P, Any], Doc( """ The function to call after the response is sent. It can be a regular `def` function or an `async def` function. """ ), ], *args: P.args, **kwargs: P.kwargs, ) -> None: """ Add a function to be called in the background after the response is sent. Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). """ return super().add_task(func, *args, **kwargs)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/utils.py
fastapi/utils.py
import re import warnings from collections.abc import MutableMapping from typing import ( TYPE_CHECKING, Any, Optional, Union, ) from weakref import WeakKeyDictionary import fastapi from fastapi._compat import ( BaseConfig, ModelField, PydanticSchemaGenerationError, Undefined, UndefinedType, Validator, annotation_is_pydantic_v1, ) from fastapi.datastructures import DefaultPlaceholder, DefaultType from fastapi.exceptions import FastAPIDeprecationWarning, PydanticV1NotSupportedError from pydantic import BaseModel from pydantic.fields import FieldInfo from typing_extensions import Literal from ._compat import v2 if TYPE_CHECKING: # pragma: nocover from .routing import APIRoute # Cache for `create_cloned_field` _CLONED_TYPES_CACHE: MutableMapping[type[BaseModel], type[BaseModel]] = ( WeakKeyDictionary() ) def is_body_allowed_for_status_code(status_code: Union[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 if status_code in { "default", "1XX", "2XX", "3XX", "4XX", "5XX", }: return True current_status_code = int(status_code) return not (current_status_code < 200 or current_status_code in {204, 205, 304}) def get_path_param_names(path: str) -> set[str]: return set(re.findall("{(.*?)}", path)) _invalid_args_message = ( "Invalid args for response field! Hint: " "check that {type_} is a valid Pydantic field type. " "If you are using a return type annotation that is not a valid Pydantic " "field (e.g. Union[Response, dict, None]) you can disable generating the " "response model from the type annotation with the path operation decorator " "parameter response_model=None. Read more: " "https://fastapi.tiangolo.com/tutorial/response-model/" ) def create_model_field( name: str, type_: Any, class_validators: Optional[dict[str, Validator]] = None, default: Optional[Any] = Undefined, required: Union[bool, UndefinedType] = Undefined, model_config: Union[type[BaseConfig], None] = None, field_info: Optional[FieldInfo] = None, alias: Optional[str] = None, mode: Literal["validation", "serialization"] = "validation", version: Literal["1", "auto"] = "auto", ) -> ModelField: if annotation_is_pydantic_v1(type_): raise PydanticV1NotSupportedError( "pydantic.v1 models are no longer supported by FastAPI." f" Please update the response model {type_!r}." ) class_validators = class_validators or {} field_info = field_info or FieldInfo(annotation=type_, default=default, alias=alias) kwargs = {"mode": mode, "name": name, "field_info": field_info} try: return v2.ModelField(**kwargs) # type: ignore[return-value,arg-type] except PydanticSchemaGenerationError: raise fastapi.exceptions.FastAPIError( _invalid_args_message.format(type_=type_) ) from None def create_cloned_field( field: ModelField, *, cloned_types: Optional[MutableMapping[type[BaseModel], type[BaseModel]]] = None, ) -> ModelField: return field def generate_operation_id_for_path( *, name: str, path: str, method: str ) -> str: # pragma: nocover warnings.warn( message="fastapi.utils.generate_operation_id_for_path() was deprecated, " "it is not used internally, and will be removed soon", category=FastAPIDeprecationWarning, stacklevel=2, ) operation_id = f"{name}{path}" operation_id = re.sub(r"\W", "_", operation_id) operation_id = f"{operation_id}_{method.lower()}" return operation_id def generate_unique_id(route: "APIRoute") -> str: operation_id = f"{route.name}{route.path_format}" operation_id = re.sub(r"\W", "_", operation_id) assert route.methods operation_id = f"{operation_id}_{list(route.methods)[0].lower()}" return operation_id def deep_dict_update(main_dict: dict[Any, Any], update_dict: dict[Any, Any]) -> None: for key, value in update_dict.items(): if ( key in main_dict and isinstance(main_dict[key], dict) and isinstance(value, dict) ): deep_dict_update(main_dict[key], value) elif ( key in main_dict and isinstance(main_dict[key], list) and isinstance(update_dict[key], list) ): main_dict[key] = main_dict[key] + update_dict[key] else: main_dict[key] = value def get_value_or_default( first_item: Union[DefaultPlaceholder, DefaultType], *extra_items: Union[DefaultPlaceholder, DefaultType], ) -> Union[DefaultPlaceholder, DefaultType]: """ Pass items or `DefaultPlaceholder`s by descending priority. The first one to _not_ be a `DefaultPlaceholder` will be returned. Otherwise, the first item (a `DefaultPlaceholder`) will be returned. """ items = (first_item,) + extra_items for item in items: if not isinstance(item, DefaultPlaceholder): return item return first_item
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/websockets.py
fastapi/websockets.py
from starlette.websockets import WebSocket as WebSocket # noqa from starlette.websockets import WebSocketDisconnect as WebSocketDisconnect # noqa from starlette.websockets import WebSocketState as WebSocketState # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/applications.py
fastapi/applications.py
from collections.abc import Awaitable, Coroutine, Sequence from enum import Enum from typing import ( Annotated, Any, Callable, Optional, TypeVar, Union, ) from annotated_doc import Doc from fastapi import routing from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.exception_handlers import ( http_exception_handler, request_validation_exception_handler, websocket_request_validation_exception_handler, ) from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) from fastapi.openapi.utils import get_openapi from fastapi.params import Depends from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import generate_unique_id from starlette.applications import Starlette from starlette.datastructures import State from starlette.exceptions import HTTPException from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.errors import ServerErrorMiddleware from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send from typing_extensions import deprecated AppType = TypeVar("AppType", bound="FastAPI") class FastAPI(Starlette): """ `FastAPI` app class, the main entrypoint to use FastAPI. Read more in the [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/). ## Example ```python from fastapi import FastAPI app = FastAPI() ``` """ def __init__( self: AppType, *, debug: Annotated[ bool, Doc( """ Boolean indicating if debug tracebacks should be returned on server errors. Read more in the [Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application). """ ), ] = False, routes: Annotated[ Optional[list[BaseRoute]], Doc( """ **Note**: you probably shouldn't use this parameter, it is inherited from Starlette and supported for compatibility. --- A list of routes to serve incoming HTTP and WebSocket requests. """ ), deprecated( """ You normally wouldn't use this parameter with FastAPI, it is inherited from Starlette and supported for compatibility. In FastAPI, you normally would use the *path operation methods*, like `app.get()`, `app.post()`, etc. """ ), ] = None, title: Annotated[ str, Doc( """ The title of the API. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI(title="ChimichangApp") ``` """ ), ] = "FastAPI", summary: Annotated[ Optional[str], Doc( """ A short summary of the API. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI(summary="Deadpond's favorite app. Nuff said.") ``` """ ), ] = None, description: Annotated[ str, Doc( ''' A description of the API. Supports Markdown (using [CommonMark syntax](https://commonmark.org/)). It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI( description=""" ChimichangApp API helps you do awesome stuff. 🚀 ## Items You can **read items**. ## Users You will be able to: * **Create users** (_not implemented_). * **Read users** (_not implemented_). """ ) ``` ''' ), ] = "", version: Annotated[ str, Doc( """ The version of the API. **Note** This is the version of your application, not the version of the OpenAPI specification nor the version of FastAPI being used. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI(version="0.0.1") ``` """ ), ] = "0.1.0", openapi_url: Annotated[ Optional[str], Doc( """ The URL where the OpenAPI schema will be served from. If you set it to `None`, no OpenAPI schema will be served publicly, and the default automatic endpoints `/docs` and `/redoc` will also be disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). **Example** ```python from fastapi import FastAPI app = FastAPI(openapi_url="/api/v1/openapi.json") ``` """ ), ] = "/openapi.json", openapi_tags: Annotated[ Optional[list[dict[str, Any]]], Doc( """ A list of tags used by OpenAPI, these are the same `tags` you can set in the *path operations*, like: * `@app.get("/users/", tags=["users"])` * `@app.get("/items/", tags=["items"])` The order of the tags can be used to specify the order shown in tools like Swagger UI, used in the automatic path `/docs`. It's not required to specify all the tags used. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. The value of each item is a `dict` containing: * `name`: The name of the tag. * `description`: A short description of the tag. [CommonMark syntax](https://commonmark.org/) MAY be used for rich text representation. * `externalDocs`: Additional external documentation for this tag. If provided, it would contain a `dict` with: * `description`: A short description of the target documentation. [CommonMark syntax](https://commonmark.org/) MAY be used for rich text representation. * `url`: The URL for the target documentation. Value MUST be in the form of a URL. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags). **Example** ```python from fastapi import FastAPI tags_metadata = [ { "name": "users", "description": "Operations with users. The **login** logic is also here.", }, { "name": "items", "description": "Manage items. So _fancy_ they have their own docs.", "externalDocs": { "description": "Items external docs", "url": "https://fastapi.tiangolo.com/", }, }, ] app = FastAPI(openapi_tags=tags_metadata) ``` """ ), ] = None, servers: Annotated[ Optional[list[dict[str, Union[str, Any]]]], Doc( """ A `list` of `dict`s with connectivity information to a target server. You would use it, for example, if your application is served from different domains and you want to use the same Swagger UI in the browser to interact with each of them (instead of having multiple browser tabs open). Or if you want to leave fixed the possible URLs. If the servers `list` is not provided, or is an empty `list`, the `servers` property in the generated OpenAPI will be: * a `dict` with a `url` value of the application's mounting point (`root_path`) if it's different from `/`. * otherwise, the `servers` property will be omitted from the OpenAPI schema. Each item in the `list` is a `dict` containing: * `url`: A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. * `description`: An optional string describing the host designated by the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for rich text representation. * `variables`: A `dict` between a variable name and its value. The value is used for substitution in the server's URL template. Read more in the [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers). **Example** ```python from fastapi import FastAPI app = FastAPI( servers=[ {"url": "https://stag.example.com", "description": "Staging environment"}, {"url": "https://prod.example.com", "description": "Production environment"}, ] ) ``` """ ), ] = None, dependencies: Annotated[ Optional[Sequence[Depends]], Doc( """ A list of global dependencies, they will be applied to each *path operation*, including in sub-routers. Read more about it in the [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/). **Example** ```python from fastapi import Depends, FastAPI from .dependencies import func_dep_1, func_dep_2 app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)]) ``` """ ), ] = None, default_response_class: Annotated[ type[Response], Doc( """ The default response class to be used. Read more in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). **Example** ```python from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI(default_response_class=ORJSONResponse) ``` """ ), ] = Default(JSONResponse), redirect_slashes: Annotated[ bool, Doc( """ Whether to detect and redirect slashes in URLs when the client doesn't use the same format. **Example** ```python from fastapi import FastAPI app = FastAPI(redirect_slashes=True) # the default @app.get("/items/") async def read_items(): return [{"item_id": "Foo"}] ``` With this app, if a client goes to `/items` (without a trailing slash), they will be automatically redirected with an HTTP status code of 307 to `/items/`. """ ), ] = True, docs_url: Annotated[ Optional[str], Doc( """ The path to the automatic interactive API documentation. It is handled in the browser by Swagger UI. The default URL is `/docs`. You can disable it by setting it to `None`. If `openapi_url` is set to `None`, this will be automatically disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). **Example** ```python from fastapi import FastAPI app = FastAPI(docs_url="/documentation", redoc_url=None) ``` """ ), ] = "/docs", redoc_url: Annotated[ Optional[str], Doc( """ The path to the alternative automatic interactive API documentation provided by ReDoc. The default URL is `/redoc`. You can disable it by setting it to `None`. If `openapi_url` is set to `None`, this will be automatically disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). **Example** ```python from fastapi import FastAPI app = FastAPI(docs_url="/documentation", redoc_url="redocumentation") ``` """ ), ] = "/redoc", swagger_ui_oauth2_redirect_url: Annotated[ Optional[str], Doc( """ The OAuth2 redirect endpoint for the Swagger UI. By default it is `/docs/oauth2-redirect`. This is only used if you use OAuth2 (with the "Authorize" button) with Swagger UI. """ ), ] = "/docs/oauth2-redirect", swagger_ui_init_oauth: Annotated[ Optional[dict[str, Any]], Doc( """ OAuth2 configuration for the Swagger UI, by default shown at `/docs`. Read more about the available configuration options in the [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). """ ), ] = None, middleware: Annotated[ Optional[Sequence[Middleware]], Doc( """ List of middleware to be added when creating the application. In FastAPI you would normally do this with `app.add_middleware()` instead. Read more in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). """ ), ] = None, exception_handlers: Annotated[ Optional[ dict[ Union[int, type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]], ] ], Doc( """ A dictionary with handlers for exceptions. In FastAPI, you would normally use the decorator `@app.exception_handler()`. Read more in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). """ ), ] = None, on_startup: Annotated[ Optional[Sequence[Callable[[], Any]]], Doc( """ A list of startup event handler functions. You should instead use the `lifespan` handlers. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, on_shutdown: Annotated[ Optional[Sequence[Callable[[], Any]]], Doc( """ A list of shutdown event handler functions. You should instead use the `lifespan` handlers. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, lifespan: Annotated[ Optional[Lifespan[AppType]], Doc( """ A `Lifespan` context manager handler. This replaces `startup` and `shutdown` functions with a single context manager. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, terms_of_service: Annotated[ Optional[str], Doc( """ A URL to the Terms of Service for your API. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more at the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python app = FastAPI(terms_of_service="http://example.com/terms/") ``` """ ), ] = None, contact: Annotated[ Optional[dict[str, Union[str, Any]]], Doc( """ A dictionary with the contact information for the exposed API. It can contain several fields. * `name`: (`str`) The name of the contact person/organization. * `url`: (`str`) A URL pointing to the contact information. MUST be in the format of a URL. * `email`: (`str`) The email address of the contact person/organization. MUST be in the format of an email address. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more at the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python app = FastAPI( contact={ "name": "Deadpoolio the Amazing", "url": "http://x-force.example.com/contact/", "email": "dp@x-force.example.com", } ) ``` """ ), ] = None, license_info: Annotated[ Optional[dict[str, Union[str, Any]]], Doc( """ A dictionary with the license information for the exposed API. It can contain several fields. * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The license name used for the API. * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. * `url`: (`str`) A URL to the license used for the API. This MUST be the format of a URL. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more at the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python app = FastAPI( license_info={ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html", } ) ``` """ ), ] = None, openapi_prefix: Annotated[ str, Doc( """ A URL prefix for the OpenAPI URL. """ ), deprecated( """ "openapi_prefix" has been deprecated in favor of "root_path", which follows more closely the ASGI standard, is simpler, and more automatic. """ ), ] = "", root_path: Annotated[ str, Doc( """ A path prefix handled by a proxy that is not seen by the application but is seen by external clients, which affects things like Swagger UI. Read more about it at the [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/). **Example** ```python from fastapi import FastAPI app = FastAPI(root_path="/api/v1") ``` """ ), ] = "", root_path_in_servers: Annotated[ bool, Doc( """ To disable automatically generating the URLs in the `servers` field in the autogenerated OpenAPI using the `root_path`. Read more about it in the [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root_path). **Example** ```python from fastapi import FastAPI app = FastAPI(root_path_in_servers=False) ``` """ ), ] = True, responses: Annotated[ Optional[dict[Union[int, str], dict[str, Any]]], Doc( """ Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). And in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, callbacks: Annotated[ Optional[list[BaseRoute]], Doc( """ OpenAPI callbacks that should apply to all *path operations*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, webhooks: Annotated[ Optional[routing.APIRouter], Doc( """ Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't depend on specific *path operations*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0. Read more about it in the [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). """ ), ] = None, deprecated: Annotated[ Optional[bool], Doc( """ Mark all *path operations* as deprecated. You probably don't need it, but it's available. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) all the *path operations* in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, swagger_ui_parameters: Annotated[ Optional[dict[str, Any]], Doc( """ Parameters to configure Swagger UI, the autogenerated interactive API documentation (by default at `/docs`). Read more about it in the [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), separate_input_output_schemas: Annotated[ bool, Doc( """ Whether to generate separate OpenAPI schemas for request body and response body when the results would be more precise. This is particularly useful when automatically generating clients. For example, if you have a model like: ```python from pydantic import BaseModel class Item(BaseModel): name: str tags: list[str] = [] ``` When `Item` is used for input, a request body, `tags` is not required, the client doesn't have to provide it. But when using `Item` for output, for a response body, `tags` is always available because it has a default value, even if it's just an empty list. So, the client should be able to always expect it. In this case, there would be two different schemas, one for input and another one for output. """ ), ] = True, openapi_external_docs: Annotated[ Optional[dict[str, Any]], Doc( """ This field allows you to provide additional external documentation links. If provided, it must be a dictionary containing: * `description`: A brief description of the external documentation. * `url`: The URL pointing to the external documentation. The value **MUST** be a valid URL format. **Example**: ```python from fastapi import FastAPI external_docs = { "description": "Detailed API Reference", "url": "https://example.com/api-docs", } app = FastAPI(openapi_external_docs=external_docs) ``` """ ), ] = None, **extra: Annotated[ Any, Doc( """ Extra keyword arguments to be stored in the app, not used by FastAPI anywhere. """ ), ], ) -> None: self.debug = debug self.title = title self.summary = summary self.description = description self.version = version self.terms_of_service = terms_of_service self.contact = contact self.license_info = license_info self.openapi_url = openapi_url self.openapi_tags = openapi_tags self.root_path_in_servers = root_path_in_servers self.docs_url = docs_url self.redoc_url = redoc_url self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url self.swagger_ui_init_oauth = swagger_ui_init_oauth self.swagger_ui_parameters = swagger_ui_parameters self.servers = servers or [] self.separate_input_output_schemas = separate_input_output_schemas self.openapi_external_docs = openapi_external_docs self.extra = extra self.openapi_version: Annotated[ str, Doc( """ The version string of OpenAPI. FastAPI will generate OpenAPI version 3.1.0, and will output that as the OpenAPI version. But some tools, even though they might be compatible with OpenAPI 3.1.0, might not recognize it as a valid. So you could override this value to trick those tools into using the generated OpenAPI. Have in mind that this is a hack. But if you avoid using features added in OpenAPI 3.1.0, it might work for your use case. This is not passed as a parameter to the `FastAPI` class to avoid giving the false idea that FastAPI would generate a different OpenAPI schema. It is only available as an attribute. **Example** ```python from fastapi import FastAPI app = FastAPI() app.openapi_version = "3.0.2" ``` """ ), ] = "3.1.0" self.openapi_schema: Optional[dict[str, Any]] = None if self.openapi_url: assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/__init__.py
fastapi/__init__.py
"""FastAPI framework, high performance, easy to learn, fast to code, ready for production""" __version__ = "0.128.0" from starlette import status as status from .applications import FastAPI as FastAPI from .background import BackgroundTasks as BackgroundTasks from .datastructures import UploadFile as UploadFile from .exceptions import HTTPException as HTTPException from .exceptions import WebSocketException as WebSocketException from .param_functions import Body as Body from .param_functions import Cookie as Cookie from .param_functions import Depends as Depends from .param_functions import File as File from .param_functions import Form as Form from .param_functions import Header as Header from .param_functions import Path as Path from .param_functions import Query as Query from .param_functions import Security as Security from .requests import Request as Request from .responses import Response as Response from .routing import APIRouter as APIRouter from .websockets import WebSocket as WebSocket from .websockets import WebSocketDisconnect as WebSocketDisconnect
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/types.py
fastapi/types.py
import types from enum import Enum from typing import Any, Callable, Optional, TypeVar, Union from pydantic import BaseModel DecoratedCallable = TypeVar("DecoratedCallable", bound=Callable[..., Any]) UnionType = getattr(types, "UnionType", Union) ModelNameMap = dict[Union[type[BaseModel], type[Enum]], str] IncEx = Union[set[int], set[str], dict[int, Any], dict[str, Any]] DependencyCacheKey = tuple[Optional[Callable[..., Any]], tuple[str, ...], str]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/responses.py
fastapi/responses.py
from typing import Any from starlette.responses import FileResponse as FileResponse # noqa from starlette.responses import HTMLResponse as HTMLResponse # noqa from starlette.responses import JSONResponse as JSONResponse # noqa from starlette.responses import PlainTextResponse as PlainTextResponse # noqa from starlette.responses import RedirectResponse as RedirectResponse # noqa from starlette.responses import Response as Response # noqa from starlette.responses import StreamingResponse as StreamingResponse # noqa try: import ujson except ImportError: # pragma: nocover ujson = None # type: ignore try: import orjson except ImportError: # pragma: nocover orjson = None # type: ignore class UJSONResponse(JSONResponse): """ JSON response using the high-performance ujson library to serialize data to JSON. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). """ def render(self, content: Any) -> bytes: assert ujson is not None, "ujson must be installed to use UJSONResponse" return ujson.dumps(content, ensure_ascii=False).encode("utf-8") class ORJSONResponse(JSONResponse): """ JSON response using the high-performance orjson library to serialize data to JSON. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/). """ def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed to use ORJSONResponse" return orjson.dumps( content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/routing.py
fastapi/routing.py
import email.message import functools import inspect import json from collections.abc import ( AsyncIterator, Awaitable, Collection, Coroutine, Mapping, Sequence, ) from contextlib import AsyncExitStack, asynccontextmanager from enum import Enum, IntEnum from typing import ( Annotated, Any, Callable, Optional, Union, ) from annotated_doc import Doc from fastapi import params from fastapi._compat import ( ModelField, Undefined, annotation_is_pydantic_v1, lenient_issubclass, ) from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( _should_embed_body_fields, get_body_field, get_dependant, get_flat_dependant, get_parameterless_sub_dependant, get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from fastapi.exceptions import ( EndpointContext, FastAPIError, PydanticV1NotSupportedError, RequestValidationError, ResponseValidationError, WebSocketRequestValidationError, ) from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_cloned_field, create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, ) from starlette import routing from starlette._exception_handler import wrap_app_handling_exceptions from starlette._utils import is_async_callable from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response from starlette.routing import ( BaseRoute, Match, compile_path, get_name, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send from starlette.websockets import WebSocket from typing_extensions import deprecated # Copy of starlette.routing.request_response modified to include the # dependencies' AsyncExitStack def request_response( func: Callable[[Request], Union[Awaitable[Response], Response]], ) -> ASGIApp: """ Takes a function or coroutine `func(request) -> response`, and returns an ASGI application. """ f: Callable[[Request], Awaitable[Response]] = ( func if is_async_callable(func) else functools.partial(run_in_threadpool, func) # type:ignore ) async def app(scope: Scope, receive: Receive, send: Send) -> None: request = Request(scope, receive, send) async def app(scope: Scope, receive: Receive, send: Send) -> None: # Starts customization response_awaited = False async with AsyncExitStack() as request_stack: scope["fastapi_inner_astack"] = request_stack async with AsyncExitStack() as function_stack: scope["fastapi_function_astack"] = function_stack response = await f(request) await response(scope, receive, send) # Continues customization response_awaited = True if not response_awaited: raise FastAPIError( "Response not awaited. There's a high chance that the " "application code is raising an exception and a dependency with yield " "has a block with a bare except, or a block with except Exception, " "and is not raising the exception again. Read more about it in the " "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" ) # Same as in Starlette await wrap_app_handling_exceptions(app, request)(scope, receive, send) return app # Copy of starlette.routing.websocket_session modified to include the # dependencies' AsyncExitStack def websocket_session( func: Callable[[WebSocket], Awaitable[None]], ) -> ASGIApp: """ Takes a coroutine `func(session)`, and returns an ASGI application. """ # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async" async def app(scope: Scope, receive: Receive, send: Send) -> None: session = WebSocket(scope, receive=receive, send=send) async def app(scope: Scope, receive: Receive, send: Send) -> None: async with AsyncExitStack() as request_stack: scope["fastapi_inner_astack"] = request_stack async with AsyncExitStack() as function_stack: scope["fastapi_function_astack"] = function_stack await func(session) # Same as in Starlette await wrap_app_handling_exceptions(app, session)(scope, receive, send) return app def _merge_lifespan_context( original_context: Lifespan[Any], nested_context: Lifespan[Any] ) -> Lifespan[Any]: @asynccontextmanager async def merged_lifespan( app: AppType, ) -> AsyncIterator[Optional[Mapping[str, Any]]]: 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: yield None # old ASGI compatibility else: yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} return merged_lifespan # type: ignore[return-value] # Cache for endpoint context to avoid re-extracting on every request _endpoint_context_cache: dict[int, EndpointContext] = {} def _extract_endpoint_context(func: Any) -> EndpointContext: """Extract endpoint context with caching to avoid repeated file I/O.""" func_id = id(func) if func_id in _endpoint_context_cache: return _endpoint_context_cache[func_id] try: ctx: EndpointContext = {} if (source_file := inspect.getsourcefile(func)) is not None: ctx["file"] = source_file if (line_number := inspect.getsourcelines(func)[1]) is not None: ctx["line"] = line_number if (func_name := getattr(func, "__name__", None)) is not None: ctx["function"] = func_name except Exception: ctx = EndpointContext() _endpoint_context_cache[func_id] = ctx return ctx async def serialize_response( *, field: Optional[ModelField] = None, response_content: Any, include: Optional[IncEx] = None, exclude: Optional[IncEx] = 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, ) -> Any: if field: errors = [] if is_coroutine: value, errors_ = field.validate(response_content, {}, loc=("response",)) else: value, errors_ = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if isinstance(errors_, list): errors.extend(errors_) if errors: ctx = endpoint_ctx or EndpointContext() raise ResponseValidationError( errors=errors, body=response_content, endpoint_ctx=ctx, ) return field.serialize( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) else: return jsonable_encoder(response_content) async def run_endpoint_function( *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool ) -> Any: # Only called by get_request_handler. Has been split into its own function to # facilitate profiling endpoints, since inner functions are harder to profile. assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: return await dependant.call(**values) else: return await run_in_threadpool(dependant.call, **values) 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, 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, embed_body_fields: bool = False, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = dependant.is_coroutine_callable is_body_form = body_field and isinstance(body_field.field_info, params.Form) if isinstance(response_class, DefaultPlaceholder): actual_response_class: type[Response] = response_class.value else: actual_response_class = response_class async def app(request: Request) -> Response: response: Union[Response, None] = None file_stack = request.scope.get("fastapi_middleware_astack") assert isinstance(file_stack, AsyncExitStack), ( "fastapi_middleware_astack not found in request scope" ) # Extract endpoint context for error messages endpoint_ctx = ( _extract_endpoint_context(dependant.call) if dependant.call else EndpointContext() ) if dependant.path: # For mounted sub-apps, include the mount path prefix mount_path = request.scope.get("root_path", "").rstrip("/") endpoint_ctx["path"] = f"{request.method} {mount_path}{dependant.path}" # Read body and auto-close files try: body: Any = None if body_field: if is_body_form: body = await request.form() file_stack.push_async_callback(body.close) else: body_bytes = await request.body() if body_bytes: json_body: Any = Undefined content_type_value = request.headers.get("content-type") if not content_type_value: json_body = await request.json() else: message = email.message.Message() message["content-type"] = content_type_value if message.get_content_maintype() == "application": subtype = message.get_content_subtype() if subtype == "json" or subtype.endswith("+json"): json_body = await request.json() if json_body != Undefined: body = json_body else: body = body_bytes except json.JSONDecodeError as e: validation_error = RequestValidationError( [ { "type": "json_invalid", "loc": ("body", e.pos), "msg": "JSON decode error", "input": {}, "ctx": {"error": e.msg}, } ], body=e.doc, endpoint_ctx=endpoint_ctx, ) raise validation_error from e except HTTPException: # If a middleware raises an HTTPException, it should be raised again raise except Exception as e: http_error = HTTPException( status_code=400, detail="There was an error parsing the body" ) raise http_error from e # Solve dependencies and run path operation function, auto-closing dependencies errors: list[Any] = [] async_exit_stack = request.scope.get("fastapi_inner_astack") assert isinstance(async_exit_stack, AsyncExitStack), ( "fastapi_inner_astack not found in request scope" ) solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, embed_body_fields=embed_body_fields, ) errors = solved_result.errors if not errors: raw_response = await run_endpoint_function( dependant=dependant, values=solved_result.values, is_coroutine=is_coroutine, ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = solved_result.background_tasks response = raw_response else: response_args: dict[str, Any] = { "background": solved_result.background_tasks } # If status_code was set, use it, otherwise use the default from the # response class, in the case of redirect it's 307 current_status_code = ( status_code if status_code else solved_result.response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code if solved_result.response.status_code: response_args["status_code"] = solved_result.response.status_code content = await serialize_response( field=response_field, response_content=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, exclude_defaults=response_model_exclude_defaults, exclude_none=response_model_exclude_none, is_coroutine=is_coroutine, endpoint_ctx=endpoint_ctx, ) response = actual_response_class(content, **response_args) if not is_body_allowed_for_status_code(response.status_code): response.body = b"" response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( errors, body=body, endpoint_ctx=endpoint_ctx ) raise validation_error # Return response assert response return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Optional[Any] = None, embed_body_fields: bool = False, ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: endpoint_ctx = ( _extract_endpoint_context(dependant.call) if dependant.call else EndpointContext() ) if dependant.path: # For mounted sub-apps, include the mount path prefix mount_path = websocket.scope.get("root_path", "").rstrip("/") endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}" async_exit_stack = websocket.scope.get("fastapi_inner_astack") assert isinstance(async_exit_stack, AsyncExitStack), ( "fastapi_inner_astack not found in request scope" ) solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, embed_body_fields=embed_body_fields, ) if solved_result.errors: raise WebSocketRequestValidationError( solved_result.errors, endpoint_ctx=endpoint_ctx, ) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**solved_result.values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: Optional[str] = None, dependencies: Optional[Sequence[params.Depends]] = None, dependency_overrides_provider: Optional[Any] = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependencies = list(dependencies or []) self.path_regex, self.path_format, self.param_convertors = compile_path(path) self.dependant = get_dependant( path=self.path_format, call=self.endpoint, scope="function" ) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self._flat_dependant = get_flat_dependant(self.dependant) self._embed_body_fields = _should_embed_body_fields( self._flat_dependant.body_params ) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, embed_body_fields=self._embed_body_fields, ) ) def matches(self, scope: Scope) -> tuple[Match, Scope]: match, child_scope = super().matches(scope) if match != Match.NONE: child_scope["route"] = self return match, child_scope class APIRoute(routing.Route): def __init__( self, path: str, 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, 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, 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), ) -> None: self.path = path self.endpoint = endpoint if isinstance(response_model, DefaultPlaceholder): return_annotation = get_typed_return_annotation(endpoint) if lenient_issubclass(return_annotation, Response): response_model = None else: response_model = return_annotation self.response_model = response_model self.summary = summary self.response_description = response_description self.deprecated = deprecated self.operation_id = operation_id self.response_model_include = response_model_include self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_exclude_unset = response_model_exclude_unset self.response_model_exclude_defaults = response_model_exclude_defaults self.response_model_exclude_none = response_model_exclude_none self.include_in_schema = include_in_schema self.response_class = response_class self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.openapi_extra = openapi_extra self.generate_unique_id_function = generate_unique_id_function self.tags = tags or [] self.responses = responses or {} self.name = get_name(endpoint) if name is None else name self.path_regex, self.path_format, self.param_convertors = compile_path(path) if methods is None: methods = ["GET"] self.methods: set[str] = {method.upper() for method in methods} if isinstance(generate_unique_id_function, DefaultPlaceholder): current_generate_unique_id: Callable[[APIRoute], str] = ( generate_unique_id_function.value ) else: current_generate_unique_id = generate_unique_id_function self.unique_id = self.operation_id or current_generate_unique_id(self) # normalize enums e.g. http.HTTPStatus if isinstance(status_code, IntEnum): status_code = int(status_code) self.status_code = status_code if self.response_model: assert is_body_allowed_for_status_code(status_code), ( f"Status code {status_code} must not have a response body" ) response_name = "Response_" + self.unique_id if annotation_is_pydantic_v1(self.response_model): raise PydanticV1NotSupportedError( "pydantic.v1 models are no longer supported by FastAPI." f" Please update the response model {self.response_model!r}." ) self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", ) # Create a clone of the field, so that a Pydantic submodel is not returned # as is just because it's an instance of a subclass of a more limited class # e.g. UserInDB (containing hashed_password) could be a subclass of User # that doesn't have the hashed_password. But because it's a subclass, it # would pass the validation and be returned as is. # By being a new field, no inheritance will be passed as is. A new model # will always be created. # TODO: remove when deprecating Pydantic v1 self.secure_cloned_response_field: Optional[ModelField] = ( create_cloned_field(self.response_field) ) else: self.response_field = None # type: ignore self.secure_cloned_response_field = None self.dependencies = list(dependencies or []) self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") # if a "form feed" character (page break) is found in the description text, # truncate description text to the content preceding the first "form feed" self.description = self.description.split("\f")[0].strip() response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: assert is_body_allowed_for_status_code(additional_status_code), ( f"Status code {additional_status_code} must not have a response body" ) response_name = f"Response_{additional_status_code}_{self.unique_id}" if annotation_is_pydantic_v1(model): raise PydanticV1NotSupportedError( "pydantic.v1 models are no longer supported by FastAPI." f" In responses={{}}, please update {model}." ) response_field = create_model_field( name=response_name, type_=model, mode="serialization" ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: dict[Union[int, str], ModelField] = response_fields else: self.response_fields = {} assert callable(endpoint), "An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint, scope="function" ) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self._flat_dependant = get_flat_dependant(self.dependant) self._embed_body_fields = _should_embed_body_fields( self._flat_dependant.body_params ) self.body_field = get_body_field( flat_dependant=self._flat_dependant, name=self.unique_id, embed_body_fields=self._embed_body_fields, ) self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.secure_cloned_response_field, response_model_include=self.response_model_include, response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_exclude_unset=self.response_model_exclude_unset, response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, embed_body_fields=self._embed_body_fields, ) def matches(self, scope: Scope) -> tuple[Match, Scope]: match, child_scope = super().matches(scope) if match != Match.NONE: child_scope["route"] = self return match, child_scope class APIRouter(routing.Router): """ `APIRouter` class, used to group *path operations*, for example to structure an app in multiple files. It would then be included in the `FastAPI` app, or in another `APIRouter` (ultimately included in the app). Read more about it in the [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/). ## Example ```python from fastapi import APIRouter, FastAPI app = FastAPI() router = APIRouter() @router.get("/users/", tags=["users"]) async def read_users(): return [{"username": "Rick"}, {"username": "Morty"}] app.include_router(router) ``` """ def __init__( self, *, prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", tags: Annotated[ Optional[list[Union[str, Enum]]], Doc( """ A list of tags to be applied to all the *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, dependencies: Annotated[ Optional[Sequence[params.Depends]], Doc( """ A list of dependencies (using `Depends()`) to be applied to all the *path operations* in this router. Read more about it in the [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, default_response_class: Annotated[ type[Response], Doc( """ The default response class to be used. Read more in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). """ ), ] = Default(JSONResponse), responses: Annotated[ Optional[dict[Union[int, str], dict[str, Any]]], Doc( """ Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). And in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, callbacks: Annotated[ Optional[list[BaseRoute]], Doc( """ OpenAPI callbacks that should apply to all *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, routes: Annotated[ Optional[list[BaseRoute]], Doc( """ **Note**: you probably shouldn't use this parameter, it is inherited from Starlette and supported for compatibility. --- A list of routes to serve incoming HTTP and WebSocket requests. """ ), deprecated( """ You normally wouldn't use this parameter with FastAPI, it is inherited from Starlette and supported for compatibility. In FastAPI, you normally would use the *path operation methods*, like `router.get()`, `router.post()`, etc. """ ), ] = None, redirect_slashes: Annotated[ bool, Doc( """ Whether to detect and redirect slashes in URLs when the client doesn't use the same format. """ ), ] = True, default: Annotated[ Optional[ASGIApp], Doc( """ Default function handler for this router. Used to handle 404 Not Found errors. """ ), ] = None, dependency_overrides_provider: Annotated[ Optional[Any], Doc( """ Only used internally by FastAPI to handle dependency overrides. You shouldn't need to use it. It normally points to the `FastAPI` app object. """ ), ] = None, route_class: Annotated[ type[APIRoute], Doc( """ Custom route (*path operation*) class to be used by this router. Read more about it in the
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/concurrency.py
fastapi/concurrency.py
from collections.abc import AsyncGenerator from contextlib import AbstractContextManager from contextlib import asynccontextmanager as asynccontextmanager from typing import TypeVar import anyio.to_thread from anyio import CapacityLimiter from starlette.concurrency import iterate_in_threadpool as iterate_in_threadpool # noqa from starlette.concurrency import run_in_threadpool as run_in_threadpool # noqa from starlette.concurrency import ( # noqa run_until_first_complete as run_until_first_complete, ) _T = TypeVar("_T") @asynccontextmanager async def contextmanager_in_threadpool( cm: AbstractContextManager[_T], ) -> AsyncGenerator[_T, None]: # blocking __exit__ from running waiting on a free thread # can create race conditions/deadlocks if the context manager itself # has its own internal pool (e.g. a database connection pool) # to avoid this we let __exit__ run without a capacity limit # since we're creating a new limiter for each call, any non-zero limit # works (1 is arbitrary) exit_limiter = CapacityLimiter(1) try: yield await run_in_threadpool(cm.__enter__) except Exception as e: ok = bool( await anyio.to_thread.run_sync( cm.__exit__, type(e), e, e.__traceback__, limiter=exit_limiter ) ) if not ok: raise e else: await anyio.to_thread.run_sync( cm.__exit__, None, None, None, limiter=exit_limiter )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/encoders.py
fastapi/encoders.py
import dataclasses import datetime from collections import defaultdict, deque from decimal import Decimal from enum import Enum from ipaddress import ( IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network, ) from pathlib import Path, PurePath from re import Pattern from types import GeneratorType from typing import Annotated, Any, Callable, Optional, Union from uuid import UUID from annotated_doc import Doc from fastapi.exceptions import PydanticV1NotSupportedError from fastapi.types import IncEx from pydantic import BaseModel from pydantic.color import Color from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr from pydantic_core import PydanticUndefinedType from ._compat import ( Url, is_pydantic_v1_model_instance, ) # Taken from Pydantic v1 as is def isoformat(o: Union[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]: """ Encodes a Decimal as int if there's no exponent, otherwise float This is useful when we use ConstrainedDecimal to represent Numeric(x,0) where an integer (but not int typed) is used. Encoding this as a float results in failed round-tripping between encode and parse. Our Id type is a prime example of this. >>> decimal_encoder(Decimal("1.0")) 1.0 >>> decimal_encoder(Decimal("1")) 1 >>> decimal_encoder(Decimal("NaN")) nan """ exponent = dec_value.as_tuple().exponent if isinstance(exponent, int) and exponent >= 0: return int(dec_value) else: return float(dec_value) ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = { bytes: lambda o: o.decode(), Color: str, datetime.date: isoformat, datetime.datetime: isoformat, datetime.time: isoformat, datetime.timedelta: lambda td: td.total_seconds(), Decimal: decimal_encoder, Enum: lambda o: o.value, frozenset: list, deque: list, GeneratorType: list, IPv4Address: str, IPv4Interface: str, IPv4Network: str, IPv6Address: str, IPv6Interface: str, IPv6Network: str, NameEmail: str, Path: str, Pattern: lambda o: o.pattern, SecretBytes: str, SecretStr: str, set: list, UUID: str, Url: str, AnyUrl: str, } def generate_encoders_by_class_tuples( type_encoder_map: dict[Any, Callable[[Any], Any]], ) -> dict[Callable[[Any], Any], tuple[Any, ...]]: encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict( tuple ) for type_, encoder in type_encoder_map.items(): encoders_by_class_tuples[encoder] += (type_,) return encoders_by_class_tuples encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) def jsonable_encoder( obj: Annotated[ Any, Doc( """ The input object to convert to JSON. """ ), ], include: Annotated[ Optional[IncEx], Doc( """ Pydantic's `include` parameter, passed to Pydantic models to set the fields to include. """ ), ] = None, exclude: Annotated[ Optional[IncEx], Doc( """ Pydantic's `exclude` parameter, passed to Pydantic models to set the fields to exclude. """ ), ] = None, by_alias: Annotated[ bool, Doc( """ Pydantic's `by_alias` parameter, passed to Pydantic models to define if the output should use the alias names (when provided) or the Python attribute names. In an API, if you set an alias, it's probably because you want to use it in the result, so you probably want to leave this set to `True`. """ ), ] = True, exclude_unset: Annotated[ bool, Doc( """ Pydantic's `exclude_unset` parameter, passed to Pydantic models to define if it should exclude from the output the fields that were not explicitly set (and that only had their default values). """ ), ] = False, exclude_defaults: Annotated[ bool, Doc( """ Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define if it should exclude from the output the fields that had the same default value, even when they were explicitly set. """ ), ] = False, exclude_none: Annotated[ bool, Doc( """ Pydantic's `exclude_none` parameter, passed to Pydantic models to define if it should exclude from the output any fields that have a `None` value. """ ), ] = False, custom_encoder: Annotated[ Optional[dict[Any, Callable[[Any], Any]]], Doc( """ Pydantic's `custom_encoder` parameter, passed to Pydantic models to define a custom encoder. """ ), ] = None, sqlalchemy_safe: Annotated[ bool, Doc( """ Exclude from the output any fields that start with the name `_sa`. This is mainly a hack for compatibility with SQLAlchemy objects, they store internal SQLAlchemy-specific state in attributes named with `_sa`, and those objects can't (and shouldn't be) serialized to JSON. """ ), ] = True, ) -> Any: """ Convert any object to something that can be encoded in JSON. This is used internally by FastAPI to make sure anything you return can be encoded as JSON before it is sent to the client. You can also use it yourself, for example to convert objects before saving them in a database that supports only JSON. Read more about it in the [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). """ custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: return custom_encoder[type(obj)](obj) else: for encoder_type, encoder_instance in custom_encoder.items(): if isinstance(obj, encoder_type): return encoder_instance(obj) if include is not None and not isinstance(include, (set, dict)): include = set(include) if exclude is not None and not isinstance(exclude, (set, dict)): exclude = set(exclude) if isinstance(obj, BaseModel): obj_dict = obj.model_dump( mode="json", include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, exclude_defaults=exclude_defaults, ) return jsonable_encoder( obj_dict, exclude_none=exclude_none, exclude_defaults=exclude_defaults, sqlalchemy_safe=sqlalchemy_safe, ) if dataclasses.is_dataclass(obj): assert not isinstance(obj, type) obj_dict = dataclasses.asdict(obj) return jsonable_encoder( obj_dict, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) if isinstance(obj, Enum): return obj.value if isinstance(obj, PurePath): return str(obj) if isinstance(obj, (str, int, float, type(None))): return obj if isinstance(obj, PydanticUndefinedType): return None if isinstance(obj, dict): encoded_dict = {} allowed_keys = set(obj.keys()) if include is not None: allowed_keys &= set(include) if exclude is not None: allowed_keys -= set(exclude) for key, value in obj.items(): if ( ( not sqlalchemy_safe or (not isinstance(key, str)) or (not key.startswith("_sa")) ) and (value is not None or not exclude_none) and key in allowed_keys ): encoded_key = jsonable_encoder( key, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) encoded_value = jsonable_encoder( value, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) encoded_dict[encoded_key] = encoded_value return encoded_dict if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): encoded_list = [] for item in obj: encoded_list.append( jsonable_encoder( item, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) ) return encoded_list if type(obj) in ENCODERS_BY_TYPE: return ENCODERS_BY_TYPE[type(obj)](obj) for encoder, classes_tuple in encoders_by_class_tuples.items(): if isinstance(obj, classes_tuple): return encoder(obj) if is_pydantic_v1_model_instance(obj): raise PydanticV1NotSupportedError( "pydantic.v1 models are no longer supported by FastAPI." f" Please update the model {obj!r}." ) try: data = dict(obj) except Exception as e: errors: list[Exception] = [] errors.append(e) try: data = vars(obj) except Exception as e: errors.append(e) raise ValueError(errors) from e return jsonable_encoder( data, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/cors.py
fastapi/middleware/cors.py
from starlette.middleware.cors import CORSMiddleware as CORSMiddleware # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/httpsredirect.py
fastapi/middleware/httpsredirect.py
from starlette.middleware.httpsredirect import ( # noqa HTTPSRedirectMiddleware as HTTPSRedirectMiddleware, )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/gzip.py
fastapi/middleware/gzip.py
from starlette.middleware.gzip import GZipMiddleware as GZipMiddleware # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/asyncexitstack.py
fastapi/middleware/asyncexitstack.py
from contextlib import AsyncExitStack from starlette.types import ASGIApp, Receive, Scope, Send # Used mainly to close files after the request is done, dependencies are closed # in their own AsyncExitStack class AsyncExitStackMiddleware: def __init__( self, app: ASGIApp, context_name: str = "fastapi_middleware_astack" ) -> None: self.app = app self.context_name = context_name async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: async with AsyncExitStack() as stack: scope[self.context_name] = stack await self.app(scope, receive, send)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/trustedhost.py
fastapi/middleware/trustedhost.py
from starlette.middleware.trustedhost import ( # noqa TrustedHostMiddleware as TrustedHostMiddleware, )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/__init__.py
fastapi/middleware/__init__.py
from starlette.middleware import Middleware as Middleware
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/middleware/wsgi.py
fastapi/middleware/wsgi.py
from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/dependencies/models.py
fastapi/dependencies/models.py
import inspect import sys from dataclasses import dataclass, field from functools import cached_property, partial from typing import Any, Callable, Optional, Union 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 else: # pragma: no cover from asyncio import iscoroutinefunction def _unwrapped_call(call: Optional[Callable[..., Any]]) -> Any: if call is None: return call # pragma: no cover unwrapped = inspect.unwrap(_impartial(call)) return unwrapped def _impartial(func: Callable[..., Any]) -> Callable[..., Any]: while isinstance(func, partial): func = func.func return func @dataclass class Dependant: path_params: list[ModelField] = field(default_factory=list) query_params: list[ModelField] = field(default_factory=list) header_params: list[ModelField] = field(default_factory=list) 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 use_cache: bool = True path: Optional[str] = None scope: Union[Literal["function", "request"], None] = None @cached_property def oauth_scopes(self) -> list[str]: scopes = self.parent_oauth_scopes.copy() if self.parent_oauth_scopes else [] # This doesn't use a set to preserve order, just in case for scope in self.own_oauth_scopes or []: if scope not in scopes: scopes.append(scope) return scopes @cached_property def cache_key(self) -> DependencyCacheKey: scopes_for_cache = ( tuple(sorted(set(self.oauth_scopes or []))) if self._uses_scopes else () ) return ( self.call, scopes_for_cache, self.computed_scope or "", ) @cached_property def _uses_scopes(self) -> bool: if self.own_oauth_scopes: return True if self.security_scopes_param_name is not None: return True if self._is_security_scheme: return True for sub_dep in self.dependencies: if sub_dep._uses_scopes: return True return False @cached_property def _is_security_scheme(self) -> bool: if self.call is None: return False # pragma: no cover unwrapped = _unwrapped_call(self.call) return isinstance(unwrapped, SecurityBase) # Mainly to get the type of SecurityBase, but it's the same self.call @cached_property def _security_scheme(self) -> SecurityBase: unwrapped = _unwrapped_call(self.call) assert isinstance(unwrapped, SecurityBase) return unwrapped @cached_property def _security_dependencies(self) -> list["Dependant"]: security_deps = [dep for dep in self.dependencies if dep._is_security_scheme] return security_deps @cached_property def is_gen_callable(self) -> bool: if self.call is None: return False # pragma: no cover if inspect.isgeneratorfunction( _impartial(self.call) ) or inspect.isgeneratorfunction(_unwrapped_call(self.call)): return True if inspect.isclass(_unwrapped_call(self.call)): return False dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004 if dunder_call is None: return False # pragma: no cover if inspect.isgeneratorfunction( _impartial(dunder_call) ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_call)): return True dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004 if dunder_unwrapped_call is None: return False # pragma: no cover if inspect.isgeneratorfunction( _impartial(dunder_unwrapped_call) ) or inspect.isgeneratorfunction(_unwrapped_call(dunder_unwrapped_call)): return True return False @cached_property def is_async_gen_callable(self) -> bool: if self.call is None: return False # pragma: no cover if inspect.isasyncgenfunction( _impartial(self.call) ) or inspect.isasyncgenfunction(_unwrapped_call(self.call)): return True if inspect.isclass(_unwrapped_call(self.call)): return False dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004 if dunder_call is None: return False # pragma: no cover if inspect.isasyncgenfunction( _impartial(dunder_call) ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_call)): return True dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004 if dunder_unwrapped_call is None: return False # pragma: no cover if inspect.isasyncgenfunction( _impartial(dunder_unwrapped_call) ) or inspect.isasyncgenfunction(_unwrapped_call(dunder_unwrapped_call)): return True return False @cached_property def is_coroutine_callable(self) -> bool: if self.call is None: return False # pragma: no cover if inspect.isroutine(_impartial(self.call)) and iscoroutinefunction( _impartial(self.call) ): return True if inspect.isroutine(_unwrapped_call(self.call)) and iscoroutinefunction( _unwrapped_call(self.call) ): return True if inspect.isclass(_unwrapped_call(self.call)): return False dunder_call = getattr(_impartial(self.call), "__call__", None) # noqa: B004 if dunder_call is None: return False # pragma: no cover if iscoroutinefunction(_impartial(dunder_call)) or iscoroutinefunction( _unwrapped_call(dunder_call) ): return True dunder_unwrapped_call = getattr(_unwrapped_call(self.call), "__call__", None) # noqa: B004 if dunder_unwrapped_call is None: return False # pragma: no cover if iscoroutinefunction( _impartial(dunder_unwrapped_call) ) or iscoroutinefunction(_unwrapped_call(dunder_unwrapped_call)): return True return False @cached_property def computed_scope(self) -> Union[str, None]: if self.scope: return self.scope if self.is_gen_callable or self.is_async_gen_callable: return "request" return None
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/dependencies/utils.py
fastapi/dependencies/utils.py
import dataclasses import inspect import sys from collections.abc import Coroutine, Mapping, Sequence from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Annotated, Any, Callable, ForwardRef, Optional, Union, cast, ) import anyio from fastapi import params from fastapi._compat import ( ModelField, RequiredParam, Undefined, _regenerate_error_with_loc, copy_field_info, create_body_model, evaluate_forwardref, field_annotation_is_scalar, get_cached_model_fields, get_missing_field_error, is_bytes_field, is_bytes_sequence_field, is_scalar_field, is_scalar_sequence_field, is_sequence_field, is_uploadfile_or_nonable_uploadfile_annotation, is_uploadfile_sequence_annotation, lenient_issubclass, sequence_types, serialize_sequence_value, value_is_sequence, ) from fastapi.background import BackgroundTasks from fastapi.concurrency import ( asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant from fastapi.exceptions import DependencyScopeError from fastapi.logger import logger from fastapi.security.oauth2 import SecurityScopes from fastapi.types import DependencyCacheKey from fastapi.utils import create_model_field, get_path_param_names from pydantic import BaseModel from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import ( FormData, Headers, ImmutableMultiDict, QueryParams, UploadFile, ) from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket from typing_extensions import Literal, get_args, get_origin multipart_not_installed_error = ( 'Form data requires "python-multipart" to be installed. \n' 'You can install "python-multipart" with: \n\n' "pip install python-multipart\n" ) multipart_incorrect_install_error = ( 'Form data requires "python-multipart" to be installed. ' 'It seems you installed "multipart" instead. \n' 'You can remove "multipart" with: \n\n' "pip uninstall multipart\n\n" 'And then install "python-multipart" with: \n\n' "pip install python-multipart\n" ) def ensure_multipart_is_installed() -> None: try: from python_multipart import __version__ # Import an attribute that can be mocked/deleted in testing assert __version__ > "0.0.12" except (ImportError, AssertionError): try: # __version__ is available in both multiparts, and can be mocked from multipart import __version__ # type: ignore[no-redef,import-untyped] assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import ( # type: ignore[import-untyped] parse_options_header, ) assert parse_options_header except ImportError: logger.error(multipart_incorrect_install_error) raise RuntimeError(multipart_incorrect_install_error) from None except ImportError: logger.error(multipart_not_installed_error) raise RuntimeError(multipart_not_installed_error) from None def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable(depends.dependency), ( "A parameter-less dependency must have a callable dependency" ) own_oauth_scopes: list[str] = [] if isinstance(depends, params.Security) and depends.scopes: own_oauth_scopes.extend(depends.scopes) return get_dependant( path=path, call=depends.dependency, scope=depends.scope, own_oauth_scopes=own_oauth_scopes, ) def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: Optional[list[DependencyCacheKey]] = None, parent_oauth_scopes: Optional[list[str]] = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) use_parent_oauth_scopes = (parent_oauth_scopes or []) + ( dependant.oauth_scopes or [] ) flat_dependant = Dependant( path_params=dependant.path_params.copy(), query_params=dependant.query_params.copy(), header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), name=dependant.name, call=dependant.call, request_param_name=dependant.request_param_name, websocket_param_name=dependant.websocket_param_name, http_connection_param_name=dependant.http_connection_param_name, response_param_name=dependant.response_param_name, background_tasks_param_name=dependant.background_tasks_param_name, security_scopes_param_name=dependant.security_scopes_param_name, own_oauth_scopes=dependant.own_oauth_scopes, parent_oauth_scopes=use_parent_oauth_scopes, use_cache=dependant.use_cache, path=dependant.path, scope=dependant.scope, ) for sub_dependant in dependant.dependencies: if skip_repeats and sub_dependant.cache_key in visited: continue flat_sub = get_flat_dependant( sub_dependant, skip_repeats=skip_repeats, visited=visited, parent_oauth_scopes=flat_dependant.oauth_scopes, ) flat_dependant.dependencies.append(flat_sub) flat_dependant.path_params.extend(flat_sub.path_params) flat_dependant.query_params.extend(flat_sub.query_params) flat_dependant.header_params.extend(flat_sub.header_params) flat_dependant.cookie_params.extend(flat_sub.cookie_params) flat_dependant.body_params.extend(flat_sub.body_params) flat_dependant.dependencies.extend(flat_sub.dependencies) return flat_dependant def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]: if not fields: return fields first_field = fields[0] if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_cached_model_fields(first_field.type_) return fields_to_extract return fields def get_flat_params(dependant: Dependant) -> list[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) path_params = _get_flat_fields_from_params(flat_dependant.path_params) query_params = _get_flat_fields_from_params(flat_dependant.query_params) header_params = _get_flat_fields_from_params(flat_dependant.header_params) cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) return path_params + query_params + header_params + cookie_params def _get_signature(call: Callable[..., Any]) -> inspect.Signature: if sys.version_info >= (3, 10): try: signature = inspect.signature(call, eval_str=True) except NameError: # Handle type annotations with if TYPE_CHECKING, not used by FastAPI # e.g. dependency return types signature = inspect.signature(call) else: signature = inspect.signature(call) return signature def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = _get_signature(call) unwrapped = inspect.unwrap(call) globalns = getattr(unwrapped, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param.annotation, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any: if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) if annotation is type(None): return None return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = _get_signature(call) unwrapped = inspect.unwrap(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(unwrapped, "__globals__", {}) return get_typed_annotation(annotation, globalns) def get_dependant( *, path: str, call: Callable[..., Any], name: Optional[str] = None, own_oauth_scopes: Optional[list[str]] = None, parent_oauth_scopes: Optional[list[str]] = None, use_cache: bool = True, scope: Union[Literal["function", "request"], None] = None, ) -> Dependant: dependant = Dependant( call=call, name=name, path=path, use_cache=use_cache, scope=scope, own_oauth_scopes=own_oauth_scopes, parent_oauth_scopes=parent_oauth_scopes, ) current_scopes = (parent_oauth_scopes or []) + (own_oauth_scopes or []) path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names param_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) if param_details.depends is not None: assert param_details.depends.dependency if ( (dependant.is_gen_callable or dependant.is_async_gen_callable) and dependant.computed_scope == "request" and param_details.depends.scope == "function" ): assert dependant.call raise DependencyScopeError( f'The dependency "{dependant.call.__name__}" has a scope of ' '"request", it cannot depend on dependencies with scope "function".' ) sub_own_oauth_scopes: list[str] = [] if isinstance(param_details.depends, params.Security): if param_details.depends.scopes: sub_own_oauth_scopes = list(param_details.depends.scopes) sub_dependant = get_dependant( path=path, call=param_details.depends.dependency, name=param_name, own_oauth_scopes=sub_own_oauth_scopes, parent_oauth_scopes=current_scopes, use_cache=param_details.depends.use_cache, scope=param_details.depends.scope, ) dependant.dependencies.append(sub_dependant) continue if add_non_field_param_to_dependency( param_name=param_name, type_annotation=param_details.type_annotation, dependant=dependant, ): assert param_details.field is None, ( f"Cannot specify multiple FastAPI annotations for {param_name!r}" ) continue assert param_details.field is not None if isinstance(param_details.field.field_info, params.Body): dependant.body_params.append(param_details.field) else: add_param_to_fields(field=param_details.field, dependant=dependant) return dependant def add_non_field_param_to_dependency( *, param_name: str, type_annotation: Any, dependant: Dependant ) -> Optional[bool]: if lenient_issubclass(type_annotation, Request): dependant.request_param_name = param_name return True elif lenient_issubclass(type_annotation, WebSocket): dependant.websocket_param_name = param_name return True elif lenient_issubclass(type_annotation, HTTPConnection): dependant.http_connection_param_name = param_name return True elif lenient_issubclass(type_annotation, Response): dependant.response_param_name = param_name return True elif lenient_issubclass(type_annotation, StarletteBackgroundTasks): dependant.background_tasks_param_name = param_name return True elif lenient_issubclass(type_annotation, SecurityScopes): dependant.security_scopes_param_name = param_name return True return None @dataclass class ParamDetails: type_annotation: Any depends: Optional[params.Depends] field: Optional[ModelField] def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, ) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any use_annotation: Any = Any if annotation is not inspect.Signature.empty: use_annotation = annotation type_annotation = annotation # Extract Annotated info if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] fastapi_annotations = [ arg for arg in annotated_args[1:] if isinstance(arg, (FieldInfo, params.Depends)) ] fastapi_specific_annotations = [ arg for arg in fastapi_annotations if isinstance( arg, ( params.Param, params.Body, params.Depends, ), ) ] if fastapi_specific_annotations: fastapi_annotation: Union[FieldInfo, params.Depends, None] = ( fastapi_specific_annotations[-1] ) else: fastapi_annotation = None # Set default for Annotated FieldInfo if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. field_info = copy_field_info( field_info=fastapi_annotation, # type: ignore[arg-type] annotation=use_annotation, ) assert ( field_info.default == Undefined or field_info.default == RequiredParam ), ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." ) if value is not inspect.Signature.empty: assert not is_path_param, "Path parameters cannot have default values" field_info.default = value else: field_info.default = RequiredParam # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation # Get Depends from default value if isinstance(value, params.Depends): assert depends is None, ( "Cannot specify `Depends` in `Annotated` and default value" f" together for {param_name!r}" ) assert field_info is None, ( "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a" f" default value together for {param_name!r}" ) depends = value # Get FieldInfo from default value elif isinstance(value, FieldInfo): assert field_info is None, ( "Cannot specify FastAPI annotations in `Annotated` and default value" f" together for {param_name!r}" ) field_info = value # type: ignore[assignment] if isinstance(field_info, FieldInfo): field_info.annotation = type_annotation # Get Depends from type annotation if depends is not None and depends.dependency is None: # Copy `depends` before mutating it depends = copy(depends) depends = dataclasses.replace(depends, dependency=type_annotation) # Handle non-param type annotations like Request if lenient_issubclass( type_annotation, ( Request, WebSocket, HTTPConnection, Response, StarletteBackgroundTasks, SecurityScopes, ), ): assert depends is None, f"Cannot specify `Depends` for type {type_annotation!r}" assert field_info is None, ( f"Cannot specify FastAPI annotation for type {type_annotation!r}" ) # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else RequiredParam if is_path_param: # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. field_info = params.Path(annotation=use_annotation) elif is_uploadfile_or_nonable_uploadfile_annotation( type_annotation ) or is_uploadfile_sequence_annotation(type_annotation): field_info = params.File(annotation=use_annotation, default=default_value) elif not field_annotation_is_scalar(annotation=type_annotation): field_info = params.Body(annotation=use_annotation, default=default_value) else: field_info = params.Query(annotation=use_annotation, default=default_value) field = None # It's a field_info, not a dependency if field_info is not None: # Handle field_info.in_ if is_path_param: assert isinstance(field_info, params.Path), ( f"Cannot use `{field_info.__class__.__name__}` for path param" f" {param_name!r}" ) elif ( isinstance(field_info, params.Param) and getattr(field_info, "in_", None) is None ): field_info.in_ = params.ParamTypes.query use_annotation_from_field_info = use_annotation if isinstance(field_info, params.Form): ensure_multipart_is_installed() if not field_info.alias and getattr(field_info, "convert_underscores", None): alias = param_name.replace("_", "-") else: alias = field_info.alias or param_name field_info.alias = alias field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, alias=alias, required=field_info.default in (RequiredParam, Undefined), field_info=field_info, ) if is_path_param: assert is_scalar_field(field=field), ( "Path params must be of one of the supported types" ) elif isinstance(field_info, params.Query): assert ( is_scalar_field(field) or is_scalar_sequence_field(field) or ( lenient_issubclass(field.type_, BaseModel) # For Pydantic v1 and getattr(field, "shape", 1) == 1 ) ) return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = field.field_info field_info_in = getattr(field_info, "in_", None) if field_info_in == params.ParamTypes.path: dependant.path_params.append(field) elif field_info_in == params.ParamTypes.query: dependant.query_params.append(field) elif field_info_in == params.ParamTypes.header: dependant.header_params.append(field) else: assert field_info_in == params.ParamTypes.cookie, ( f"non-body parameters must be in path, query, header or cookie: {field.name}" ) dependant.cookie_params.append(field) async def _solve_generator( *, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any] ) -> Any: assert dependant.call if dependant.is_async_gen_callable: cm = asynccontextmanager(dependant.call)(**sub_values) elif dependant.is_gen_callable: cm = contextmanager_in_threadpool(contextmanager(dependant.call)(**sub_values)) return await stack.enter_async_context(cm) @dataclass class SolvedDependency: values: dict[str, Any] errors: list[Any] background_tasks: Optional[StarletteBackgroundTasks] response: Response dependency_cache: dict[DependencyCacheKey, Any] async def solve_dependencies( *, request: Union[Request, WebSocket], dependant: Dependant, body: Optional[Union[dict[str, Any], FormData]] = None, background_tasks: Optional[StarletteBackgroundTasks] = None, response: Optional[Response] = None, dependency_overrides_provider: Optional[Any] = None, dependency_cache: Optional[dict[DependencyCacheKey, Any]] = None, # TODO: remove this parameter later, no longer used, not removing it yet as some # people might be monkey patching this function (although that's not supported) async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: request_astack = request.scope.get("fastapi_inner_astack") assert isinstance(request_astack, AsyncExitStack), ( "fastapi_inner_astack not found in request scope" ) function_astack = request.scope.get("fastapi_function_astack") assert isinstance(function_astack, AsyncExitStack), ( "fastapi_function_astack not found in request scope" ) values: dict[str, Any] = {} errors: list[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore if dependency_cache is None: dependency_cache = {} for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) call = sub_dependant.call use_sub_dependant = sub_dependant if ( dependency_overrides_provider and dependency_overrides_provider.dependency_overrides ): original_call = sub_dependant.call call = getattr( dependency_overrides_provider, "dependency_overrides", {} ).get(original_call, original_call) use_path: str = sub_dependant.path # type: ignore use_sub_dependant = get_dependant( path=use_path, call=call, name=sub_dependant.name, parent_oauth_scopes=sub_dependant.oauth_scopes, scope=sub_dependant.scope, ) solved_result = await solve_dependencies( request=request, dependant=use_sub_dependant, body=body, background_tasks=background_tasks, response=response, dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, embed_body_fields=embed_body_fields, ) background_tasks = solved_result.background_tasks if solved_result.errors: errors.extend(solved_result.errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif ( use_sub_dependant.is_gen_callable or use_sub_dependant.is_async_gen_callable ): use_astack = request_astack if sub_dependant.scope == "function": use_astack = function_astack solved = await _solve_generator( dependant=use_sub_dependant, stack=use_astack, sub_values=solved_result.values, ) elif use_sub_dependant.is_coroutine_callable: solved = await call(**solved_result.values) else: solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: dependency_cache[sub_dependant.cache_key] = solved path_values, path_errors = request_params_to_args( dependant.path_params, request.path_params ) query_values, query_errors = request_params_to_args( dependant.query_params, request.query_params ) header_values, header_errors = request_params_to_args( dependant.header_params, request.headers ) cookie_values, cookie_errors = request_params_to_args( dependant.cookie_params, request.cookies ) values.update(path_values) values.update(query_values) values.update(header_values) values.update(cookie_values) errors += path_errors + query_errors + header_errors + cookie_errors if dependant.body_params: ( body_values, body_errors, ) = await request_body_to_args( # body_params checked above body_fields=dependant.body_params, received_body=body, embed_body_fields=embed_body_fields, ) values.update(body_values) errors.extend(body_errors) if dependant.http_connection_param_name: values[dependant.http_connection_param_name] = request if dependant.request_param_name and isinstance(request, Request): values[dependant.request_param_name] = request elif dependant.websocket_param_name and isinstance(request, WebSocket): values[dependant.websocket_param_name] = request if dependant.background_tasks_param_name: if background_tasks is None: background_tasks = BackgroundTasks() values[dependant.background_tasks_param_name] = background_tasks if dependant.response_param_name: values[dependant.response_param_name] = response if dependant.security_scopes_param_name: values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.oauth_scopes ) return SolvedDependency( values=values, errors=errors, background_tasks=background_tasks, response=response, dependency_cache=dependency_cache, ) def _validate_value_with_model_field( *, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...] ) -> tuple[Any, list[Any]]: if value is None: if field.required: return None, [get_missing_field_error(loc=loc)] else: return deepcopy(field.default), [] v_, errors_ = field.validate(value, values, loc=loc) if isinstance(errors_, list): new_errors = _regenerate_error_with_loc(errors=errors_, loc_prefix=()) return None, new_errors else: return v_, [] def _get_multidict_value( field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None ) -> Any: alias = alias or get_validation_alias(field) if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)): value = values.getlist(alias) else: value = values.get(alias, None) if ( value is None or ( isinstance(field.field_info, params.Form) and isinstance(value, str) # For type checks and value == "" ) or (is_sequence_field(field) and len(value) == 0) ): if field.required: return else: return deepcopy(field.default) return value def request_params_to_args( fields: Sequence[ModelField], received_params: Union[Mapping[str, Any], QueryParams, Headers], ) -> tuple[dict[str, Any], list[Any]]: values: dict[str, Any] = {} errors: list[dict[str, Any]] = [] if not fields: return values, errors first_field = fields[0] fields_to_extract = fields single_not_embedded_field = False default_convert_underscores = True if len(fields) == 1 and lenient_issubclass(first_field.type_, BaseModel): fields_to_extract = get_cached_model_fields(first_field.type_) single_not_embedded_field = True # If headers are in a Pydantic model, the way to disable convert_underscores # would be with Header(convert_underscores=False) at the Pydantic model level default_convert_underscores = getattr( first_field.field_info, "convert_underscores", True ) params_to_process: dict[str, Any] = {} processed_keys = set() for field in fields_to_extract: alias = None if isinstance(received_params, Headers): # Handle fields extracted from a Pydantic Model for a header, each field # doesn't have a FieldInfo of type Header with the default convert_underscores=True convert_underscores = getattr( field.field_info, "convert_underscores", default_convert_underscores ) if convert_underscores: alias = get_validation_alias(field) if alias == field.name: alias = alias.replace("_", "-") value = _get_multidict_value(field, received_params, alias=alias) if value is not None: params_to_process[get_validation_alias(field)] = value processed_keys.add(alias or get_validation_alias(field)) for key in received_params.keys(): if key not in processed_keys: if hasattr(received_params, "getlist"): value = received_params.getlist(key) if isinstance(value, list) and (len(value) == 1): params_to_process[key] = value[0] else: params_to_process[key] = value else: params_to_process[key] = received_params.get(key) if single_not_embedded_field: field_info = first_field.field_info assert isinstance(field_info, params.Param), ( "Params must be subclasses of Param" ) loc: tuple[str, ...] = (field_info.in_.value,) v_, errors_ = _validate_value_with_model_field( field=first_field, value=params_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in fields: value = _get_multidict_value(field, received_params) field_info = field.field_info assert isinstance(field_info, params.Param), ( "Params must be subclasses of Param" ) loc = (field_info.in_.value, get_validation_alias(field)) v_, errors_ = _validate_value_with_model_field( field=field, value=value, values=values, loc=loc ) if errors_: errors.extend(errors_) else: values[field.name] = v_ return values, errors def is_union_of_base_models(field_type: Any) -> bool: """Check if field type is a Union where all members are BaseModel subclasses.""" from fastapi.types import UnionType origin = get_origin(field_type) # Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+) if origin is not Union and origin is not UnionType: return False union_args = get_args(field_type) for arg in union_args: if not lenient_issubclass(arg, BaseModel): return False return True def _should_embed_body_fields(fields: list[ModelField]) -> bool: if not fields: return False # More than one dependency could have the same field, it would show up as multiple # fields but it's the same one, so count them by name body_param_names_set = {field.name for field in fields} # A top level field has to be a single field, not multiple if len(body_param_names_set) > 1: return True first_field = fields[0] # If it explicitly specifies it is embedded, it has to be embedded if getattr(first_field.field_info, "embed", None): return True # If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if (
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
true
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/dependencies/__init__.py
fastapi/dependencies/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/api_key.py
fastapi/security/api_key.py
from typing import Annotated, Optional, Union from annotated_doc import Doc from fastapi.openapi.models import APIKey, APIKeyIn from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class APIKeyBase(SecurityBase): def __init__( self, location: APIKeyIn, name: str, description: Union[str, None], scheme_name: Union[str, None], auto_error: bool, ): self.auto_error = auto_error self.model: APIKey = APIKey( **{"in": location}, name=name, description=description, ) self.scheme_name = scheme_name or self.__class__.__name__ def make_not_authenticated_error(self) -> HTTPException: """ The WWW-Authenticate header is not standardized for API Key authentication but the HTTP specification requires that an error of 401 "Unauthorized" must include a WWW-Authenticate header. Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized For this, this method sends a custom challenge `APIKey`. """ return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "APIKey"}, ) def check_api_key(self, api_key: Optional[str]) -> Optional[str]: if not api_key: if self.auto_error: raise self.make_not_authenticated_error() return None return api_key class APIKeyQuery(APIKeyBase): """ API key authentication using a query parameter. This defines the name of the query parameter that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the query parameter automatically and provides it as the dependency result. But it doesn't define how to send that API key to the client. ## Usage Create an instance object and use that object as the dependency in `Depends()`. The dependency result will be a string containing the key value. ## Example ```python from fastapi import Depends, FastAPI from fastapi.security import APIKeyQuery app = FastAPI() query_scheme = APIKeyQuery(name="api_key") @app.get("/items/") async def read_items(api_key: str = Depends(query_scheme)): return {"api_key": api_key} ``` """ def __init__( self, *, name: Annotated[ str, Doc("Query parameter name."), ], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the query parameter is not provided, `APIKeyQuery` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the query parameter is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a query parameter or in an HTTP Bearer token). """ ), ] = True, ): super().__init__( location=APIKeyIn.query, name=name, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> Optional[str]: api_key = request.query_params.get(self.model.name) return self.check_api_key(api_key) class APIKeyHeader(APIKeyBase): """ API key authentication using a header. This defines the name of the header that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the header automatically and provides it as the dependency result. But it doesn't define how to send that key to the client. ## Usage Create an instance object and use that object as the dependency in `Depends()`. The dependency result will be a string containing the key value. ## Example ```python from fastapi import Depends, FastAPI from fastapi.security import APIKeyHeader app = FastAPI() header_scheme = APIKeyHeader(name="x-key") @app.get("/items/") async def read_items(key: str = Depends(header_scheme)): return {"key": key} ``` """ def __init__( self, *, name: Annotated[str, Doc("Header name.")], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the header is not provided, `APIKeyHeader` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a header or in an HTTP Bearer token). """ ), ] = True, ): super().__init__( location=APIKeyIn.header, name=name, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> Optional[str]: api_key = request.headers.get(self.model.name) return self.check_api_key(api_key) class APIKeyCookie(APIKeyBase): """ API key authentication using a cookie. This defines the name of the cookie that should be provided in the request with the API key and integrates that into the OpenAPI documentation. It extracts the key value sent in the cookie automatically and provides it as the dependency result. But it doesn't define how to set that cookie. ## Usage Create an instance object and use that object as the dependency in `Depends()`. The dependency result will be a string containing the key value. ## Example ```python from fastapi import Depends, FastAPI from fastapi.security import APIKeyCookie app = FastAPI() cookie_scheme = APIKeyCookie(name="session") @app.get("/items/") async def read_items(session: str = Depends(cookie_scheme)): return {"session": session} ``` """ def __init__( self, *, name: Annotated[str, Doc("Cookie name.")], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the cookie is not provided, `APIKeyCookie` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the cookie is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a cookie or in an HTTP Bearer token). """ ), ] = True, ): super().__init__( location=APIKeyIn.cookie, name=name, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> Optional[str]: api_key = request.cookies.get(self.model.name) return self.check_api_key(api_key)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/http.py
fastapi/security/http.py
import binascii from base64 import b64decode from typing import Annotated, Optional from annotated_doc import Doc from fastapi.exceptions import HTTPException from fastapi.openapi.models import HTTPBase as HTTPBaseModel from fastapi.openapi.models import HTTPBearer as HTTPBearerModel from fastapi.security.base import SecurityBase from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class HTTPBasicCredentials(BaseModel): """ The HTTP Basic credentials given as the result of using `HTTPBasic` in a dependency. Read more about it in the [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). """ username: Annotated[str, Doc("The HTTP Basic username.")] password: Annotated[str, Doc("The HTTP Basic password.")] class HTTPAuthorizationCredentials(BaseModel): """ The HTTP authorization credentials in the result of using `HTTPBearer` or `HTTPDigest` in a dependency. The HTTP authorization header value is split by the first space. The first part is the `scheme`, the second part is the `credentials`. For example, in an HTTP Bearer token scheme, the client will send a header like: ``` Authorization: Bearer deadbeef12346 ``` In this case: * `scheme` will have the value `"Bearer"` * `credentials` will have the value `"deadbeef12346"` """ scheme: Annotated[ str, Doc( """ The HTTP authorization scheme extracted from the header value. """ ), ] credentials: Annotated[ str, Doc( """ The HTTP authorization credentials extracted from the header value. """ ), ] class HTTPBase(SecurityBase): def __init__( self, *, scheme: str, scheme_name: Optional[str] = None, description: Optional[str] = None, auto_error: bool = True, ): self.model: HTTPBaseModel = HTTPBaseModel( scheme=scheme, description=description ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error def make_authenticate_headers(self) -> dict[str, str]: return {"WWW-Authenticate": f"{self.model.scheme.title()}"} def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers=self.make_authenticate_headers(), ) async def __call__( self, request: Request ) -> Optional[HTTPAuthorizationCredentials]: authorization = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise self.make_not_authenticated_error() else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) class HTTPBasic(HTTPBase): """ HTTP Basic authentication. Ref: https://datatracker.ietf.org/doc/html/rfc7617 ## Usage Create an instance object and use that object as the dependency in `Depends()`. The dependency result will be an `HTTPBasicCredentials` object containing the `username` and the `password`. Read more about it in the [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). ## Example ```python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import HTTPBasic, HTTPBasicCredentials app = FastAPI() security = HTTPBasic() @app.get("/users/me") def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): return {"username": credentials.username, "password": credentials.password} ``` """ def __init__( self, *, scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, realm: Annotated[ Optional[str], Doc( """ HTTP Basic authentication realm. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the HTTP Basic authentication is not provided (a header), `HTTPBasic` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Basic authentication is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Basic authentication or in an HTTP Bearer token). """ ), ] = True, ): self.model = HTTPBaseModel(scheme="basic", description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.realm = realm self.auto_error = auto_error def make_authenticate_headers(self) -> dict[str, str]: if self.realm: return {"WWW-Authenticate": f'Basic realm="{self.realm}"'} return {"WWW-Authenticate": "Basic"} async def __call__( # type: ignore self, request: Request ) -> Optional[HTTPBasicCredentials]: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "basic": if self.auto_error: raise self.make_not_authenticated_error() else: return None try: data = b64decode(param).decode("ascii") except (ValueError, UnicodeDecodeError, binascii.Error) as e: raise self.make_not_authenticated_error() from e username, separator, password = data.partition(":") if not separator: raise self.make_not_authenticated_error() return HTTPBasicCredentials(username=username, password=password) class HTTPBearer(HTTPBase): """ HTTP Bearer token authentication. ## Usage Create an instance object and use that object as the dependency in `Depends()`. The dependency result will be an `HTTPAuthorizationCredentials` object containing the `scheme` and the `credentials`. ## Example ```python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer app = FastAPI() security = HTTPBearer() @app.get("/users/me") def read_current_user( credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] ): return {"scheme": credentials.scheme, "credentials": credentials.credentials} ``` """ def __init__( self, *, bearerFormat: Annotated[Optional[str], Doc("Bearer token format.")] = None, scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the HTTP Bearer token is not provided (in an `Authorization` header), `HTTPBearer` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Bearer token is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in an HTTP Bearer token or in a cookie). """ ), ] = True, ): self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error async def __call__( self, request: Request ) -> Optional[HTTPAuthorizationCredentials]: authorization = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise self.make_not_authenticated_error() else: return None if scheme.lower() != "bearer": if self.auto_error: raise self.make_not_authenticated_error() else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) class HTTPDigest(HTTPBase): """ HTTP Digest authentication. **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI, but it doesn't implement the full Digest scheme, you would need to to subclass it and implement it in your code. Ref: https://datatracker.ietf.org/doc/html/rfc7616 ## Usage Create an instance object and use that object as the dependency in `Depends()`. The dependency result will be an `HTTPAuthorizationCredentials` object containing the `scheme` and the `credentials`. ## Example ```python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest app = FastAPI() security = HTTPDigest() @app.get("/users/me") def read_current_user( credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] ): return {"scheme": credentials.scheme, "credentials": credentials.credentials} ``` """ def __init__( self, *, scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the HTTP Digest is not provided, `HTTPDigest` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Digest is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Digest or in a cookie). """ ), ] = True, ): self.model = HTTPBaseModel(scheme="digest", description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error async def __call__( self, request: Request ) -> Optional[HTTPAuthorizationCredentials]: authorization = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise self.make_not_authenticated_error() else: return None if scheme.lower() != "digest": if self.auto_error: raise self.make_not_authenticated_error() else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/open_id_connect_url.py
fastapi/security/open_id_connect_url.py
from typing import Annotated, Optional from annotated_doc import Doc from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class OpenIdConnect(SecurityBase): """ OpenID Connect authentication class. An instance of it would be used as a dependency. **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI, but it doesn't implement the full OpenIdConnect scheme, for example, it doesn't use the OpenIDConnect URL. You would need to to subclass it and implement it in your code. """ def __init__( self, *, openIdConnectUrl: Annotated[ str, Doc( """ The OpenID Connect URL. """ ), ], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OpenID Connect authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OpenID Connect or in a cookie). """ ), ] = True, ): self.model = OpenIdConnectModel( openIdConnectUrl=openIdConnectUrl, description=description ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) async def __call__(self, request: Request) -> Optional[str]: authorization = request.headers.get("Authorization") if not authorization: if self.auto_error: raise self.make_not_authenticated_error() else: return None return authorization
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/oauth2.py
fastapi/security/oauth2.py
from typing import Annotated, Any, Optional, Union, cast from annotated_doc import Doc from fastapi.exceptions import HTTPException from fastapi.openapi.models import OAuth2 as OAuth2Model from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel from fastapi.param_functions import Form from fastapi.security.base import SecurityBase from fastapi.security.utils import get_authorization_scheme_param from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class OAuth2PasswordRequestForm: """ This is a dependency class to collect the `username` and `password` as form data for an OAuth2 password flow. The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields `username` and `password`. All the initialization parameters are extracted from the request. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). ## Example ```python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordRequestForm app = FastAPI() @app.post("/login") def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): data = {} data["scopes"] = [] for scope in form_data.scopes: data["scopes"].append(scope) if form_data.client_id: data["client_id"] = form_data.client_id if form_data.client_secret: data["client_secret"] = form_data.client_secret return data ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. """ def __init__( self, *, grant_type: Annotated[ Union[str, None], Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string "password". Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it, use instead the `OAuth2PasswordRequestFormStrict` dependency. """ ), ] = None, username: Annotated[ str, Form(), Doc( """ `username` string. The OAuth2 spec requires the exact field name `username`. """ ), ], password: Annotated[ str, Form(json_schema_extra={"format": "password"}), Doc( """ `password` string. The OAuth2 spec requires the exact field name `password`. """ ), ], scope: Annotated[ str, Form(), Doc( """ A single string with actually several scopes separated by spaces. Each scope is also a string. For example, a single string with: ```python "items:read items:write users:read profile openid" ```` would represent the scopes: * `items:read` * `items:write` * `users:read` * `profile` * `openid` """ ), ] = "", client_id: Annotated[ Union[str, None], Form(), Doc( """ If there's a `client_id`, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, client_secret: Annotated[ Union[str, None], Form(json_schema_extra={"format": "password"}), Doc( """ If there's a `client_password` (and a `client_id`), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, ): self.grant_type = grant_type self.username = username self.password = password self.scopes = scope.split() self.client_id = client_id self.client_secret = client_secret class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): """ This is a dependency class to collect the `username` and `password` as form data for an OAuth2 password flow. The OAuth2 specification dictates that for a password flow the data should be collected using form data (instead of JSON) and that it should have the specific fields `username` and `password`. All the initialization parameters are extracted from the request. The only difference between `OAuth2PasswordRequestFormStrict` and `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the client to send the form field `grant_type` with the value `"password"`, which is required in the OAuth2 specification (it seems that for no particular reason), while for `OAuth2PasswordRequestForm` `grant_type` is optional. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). ## Example ```python from typing import Annotated from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordRequestForm app = FastAPI() @app.post("/login") def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]): data = {} data["scopes"] = [] for scope in form_data.scopes: data["scopes"].append(scope) if form_data.client_id: data["client_id"] = form_data.client_id if form_data.client_secret: data["client_secret"] = form_data.client_secret return data ``` Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. You could have custom internal logic to separate it by colon characters (`:`) or similar, and get the two parts `items` and `read`. Many applications do that to group and organize permissions, you could do it as well in your application, just know that that it is application specific, it's not part of the specification. grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". This dependency is strict about it. If you want to be permissive, use instead the OAuth2PasswordRequestForm dependency class. username: username string. The OAuth2 spec requires the exact field name "username". password: password string. The OAuth2 spec requires the exact field name "password". scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. "items:read items:write users:read profile openid" client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret """ def __init__( self, grant_type: Annotated[ str, Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string "password". This dependency is strict about it. If you want to be permissive, use instead the `OAuth2PasswordRequestForm` dependency class. """ ), ], username: Annotated[ str, Form(), Doc( """ `username` string. The OAuth2 spec requires the exact field name `username`. """ ), ], password: Annotated[ str, Form(), Doc( """ `password` string. The OAuth2 spec requires the exact field name `password`. """ ), ], scope: Annotated[ str, Form(), Doc( """ A single string with actually several scopes separated by spaces. Each scope is also a string. For example, a single string with: ```python "items:read items:write users:read profile openid" ```` would represent the scopes: * `items:read` * `items:write` * `users:read` * `profile` * `openid` """ ), ] = "", client_id: Annotated[ Union[str, None], Form(), Doc( """ If there's a `client_id`, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, client_secret: Annotated[ Union[str, None], Form(), Doc( """ If there's a `client_password` (and a `client_id`), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, ): super().__init__( grant_type=grant_type, username=username, password=password, scope=scope, client_id=client_id, client_secret=client_secret, ) class OAuth2(SecurityBase): """ This is the base class for OAuth2 authentication, an instance of it would be used as a dependency. All other OAuth2 classes inherit from it and customize it for each OAuth2 flow. You normally would not create a new class inheriting from it but use one of the existing subclasses, and maybe compose them if you want to support multiple flows. Read more about it in the [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/). """ def __init__( self, *, flows: Annotated[ Union[OAuthFlowsModel, dict[str, dict[str, Any]]], Doc( """ The dictionary of OAuth2 flows. """ ), ] = OAuthFlowsModel(), scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). """ ), ] = True, ): self.model = OAuth2Model( flows=cast(OAuthFlowsModel, flows), description=description ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error def make_not_authenticated_error(self) -> HTTPException: """ The OAuth 2 specification doesn't define the challenge that should be used, because a `Bearer` token is not really the only option to authenticate. But declaring any other authentication challenge would be application-specific as it's not defined in the specification. For practical reasons, this method uses the `Bearer` challenge by default, as it's probably the most common one. If you are implementing an OAuth2 authentication scheme other than the provided ones in FastAPI (based on bearer tokens), you might want to override this. Ref: https://datatracker.ietf.org/doc/html/rfc6749 """ return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) async def __call__(self, request: Request) -> Optional[str]: authorization = request.headers.get("Authorization") if not authorization: if self.auto_error: raise self.make_not_authenticated_error() else: return None return authorization class OAuth2PasswordBearer(OAuth2): """ OAuth2 flow for authentication using a bearer token obtained with a password. An instance of it would be used as a dependency. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ def __init__( self, tokenUrl: Annotated[ str, Doc( """ The URL to obtain the OAuth2 token. This would be the *path operation* that has `OAuth2PasswordRequestForm` as a dependency. """ ), ], scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, scopes: Annotated[ Optional[dict[str, str]], Doc( """ The OAuth2 scopes that would be required by the *path operations* that use this dependency. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). """ ), ] = True, refreshUrl: Annotated[ Optional[str], Doc( """ The URL to refresh the token and obtain a new one. """ ), ] = None, ): if not scopes: scopes = {} flows = OAuthFlowsModel( password=cast( Any, { "tokenUrl": tokenUrl, "refreshUrl": refreshUrl, "scopes": scopes, }, ) ) super().__init__( flows=flows, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> Optional[str]: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": if self.auto_error: raise self.make_not_authenticated_error() else: return None return param class OAuth2AuthorizationCodeBearer(OAuth2): """ OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code flow. An instance of it would be used as a dependency. """ def __init__( self, authorizationUrl: str, tokenUrl: Annotated[ str, Doc( """ The URL to obtain the OAuth2 token. """ ), ], refreshUrl: Annotated[ Optional[str], Doc( """ The URL to refresh the token and obtain a new one. """ ), ] = None, scheme_name: Annotated[ Optional[str], Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, scopes: Annotated[ Optional[dict[str, str]], Doc( """ The OAuth2 scopes that would be required by the *path operations* that use this dependency. """ ), ] = None, description: Annotated[ Optional[str], Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). """ ), ] = True, ): if not scopes: scopes = {} flows = OAuthFlowsModel( authorizationCode=cast( Any, { "authorizationUrl": authorizationUrl, "tokenUrl": tokenUrl, "refreshUrl": refreshUrl, "scopes": scopes, }, ) ) super().__init__( flows=flows, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> Optional[str]: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": if self.auto_error: raise self.make_not_authenticated_error() else: return None # pragma: nocover return param class SecurityScopes: """ This is a special class that you can define in a parameter in a dependency to obtain the OAuth2 scopes required by all the dependencies in the same chain. This way, multiple dependencies can have different scopes, even when used in the same *path operation*. And with this, you can access all the scopes required in all those dependencies in a single place. Read more about it in the [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). """ def __init__( self, scopes: Annotated[ Optional[list[str]], Doc( """ This will be filled by FastAPI. """ ), ] = None, ): self.scopes: Annotated[ list[str], Doc( """ The list of all the scopes required by dependencies. """ ), ] = scopes or [] self.scope_str: Annotated[ str, Doc( """ All the scopes required by all the dependencies in a single string separated by spaces, as defined in the OAuth2 specification. """ ), ] = " ".join(self.scopes)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/utils.py
fastapi/security/utils.py
from typing import Optional def get_authorization_scheme_param( authorization_header_value: Optional[str], ) -> tuple[str, str]: if not authorization_header_value: return "", "" scheme, _, param = authorization_header_value.partition(" ") return scheme, param
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/__init__.py
fastapi/security/__init__.py
from .api_key import APIKeyCookie as APIKeyCookie from .api_key import APIKeyHeader as APIKeyHeader from .api_key import APIKeyQuery as APIKeyQuery from .http import HTTPAuthorizationCredentials as HTTPAuthorizationCredentials from .http import HTTPBasic as HTTPBasic from .http import HTTPBasicCredentials as HTTPBasicCredentials from .http import HTTPBearer as HTTPBearer from .http import HTTPDigest as HTTPDigest from .oauth2 import OAuth2 as OAuth2 from .oauth2 import OAuth2AuthorizationCodeBearer as OAuth2AuthorizationCodeBearer from .oauth2 import OAuth2PasswordBearer as OAuth2PasswordBearer from .oauth2 import OAuth2PasswordRequestForm as OAuth2PasswordRequestForm from .oauth2 import OAuth2PasswordRequestFormStrict as OAuth2PasswordRequestFormStrict from .oauth2 import SecurityScopes as SecurityScopes from .open_id_connect_url import OpenIdConnect as OpenIdConnect
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/security/base.py
fastapi/security/base.py
from fastapi.openapi.models import SecurityBase as SecurityBaseModel class SecurityBase: model: SecurityBaseModel scheme_name: str
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/_compat/shared.py
fastapi/_compat/shared.py
import sys import types import typing import warnings from collections import deque from collections.abc import Mapping, Sequence from dataclasses import is_dataclass from typing import ( Annotated, Any, Union, ) from fastapi.types import UnionType from pydantic import BaseModel from pydantic.version import VERSION as PYDANTIC_VERSION from starlette.datastructures import UploadFile from typing_extensions import get_args, get_origin # Copy from Pydantic v2, compatible with v1 if sys.version_info < (3, 10): WithArgsTypes: tuple[Any, ...] = (typing._GenericAlias, types.GenericAlias) # type: ignore[attr-defined] else: WithArgsTypes: tuple[Any, ...] = ( typing._GenericAlias, # type: ignore[attr-defined] types.GenericAlias, types.UnionType, ) # pyright: ignore[reportAttributeAccessIssue] PYDANTIC_VERSION_MINOR_TUPLE = tuple(int(x) for x in PYDANTIC_VERSION.split(".")[:2]) PYDANTIC_V2 = PYDANTIC_VERSION_MINOR_TUPLE[0] == 2 sequence_annotation_to_type = { Sequence: list, list: list, tuple: tuple, set: set, frozenset: frozenset, deque: deque, } sequence_types = tuple(sequence_annotation_to_type.keys()) Url: type[Any] # Copy of Pydantic v2, compatible with v1 def lenient_issubclass( cls: Any, class_or_tuple: Union[type[Any], tuple[type[Any], ...], None] ) -> bool: try: return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] except TypeError: # pragma: no cover if isinstance(cls, WithArgsTypes): return False raise # pragma: no cover def _annotation_is_sequence(annotation: Union[type[Any], None]) -> bool: if lenient_issubclass(annotation, (str, bytes)): return False return lenient_issubclass(annotation, sequence_types) def field_annotation_is_sequence(annotation: Union[type[Any], None]) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if field_annotation_is_sequence(arg): return True return False return _annotation_is_sequence(annotation) or _annotation_is_sequence( get_origin(annotation) ) def value_is_sequence(value: Any) -> bool: return isinstance(value, sequence_types) and not isinstance(value, (str, bytes)) def _annotation_is_complex(annotation: Union[type[Any], None]) -> bool: return ( lenient_issubclass(annotation, (BaseModel, Mapping, UploadFile)) or _annotation_is_sequence(annotation) or is_dataclass(annotation) ) def field_annotation_is_complex(annotation: Union[type[Any], None]) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: return any(field_annotation_is_complex(arg) for arg in get_args(annotation)) if origin is Annotated: return field_annotation_is_complex(get_args(annotation)[0]) return ( _annotation_is_complex(annotation) or _annotation_is_complex(origin) or hasattr(origin, "__pydantic_core_schema__") or hasattr(origin, "__get_pydantic_core_schema__") ) def field_annotation_is_scalar(annotation: Any) -> bool: # handle Ellipsis here to make tuple[int, ...] work nicely return annotation is Ellipsis or not field_annotation_is_complex(annotation) def field_annotation_is_scalar_sequence(annotation: Union[type[Any], None]) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one_scalar_sequence = False for arg in get_args(annotation): if field_annotation_is_scalar_sequence(arg): at_least_one_scalar_sequence = True continue elif not field_annotation_is_scalar(arg): return False return at_least_one_scalar_sequence return field_annotation_is_sequence(annotation) and all( field_annotation_is_scalar(sub_annotation) for sub_annotation in get_args(annotation) ) def is_bytes_or_nonable_bytes_annotation(annotation: Any) -> bool: if lenient_issubclass(annotation, bytes): return True origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if lenient_issubclass(arg, bytes): return True return False def is_uploadfile_or_nonable_uploadfile_annotation(annotation: Any) -> bool: if lenient_issubclass(annotation, UploadFile): return True origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if lenient_issubclass(arg, UploadFile): return True return False def is_bytes_sequence_annotation(annotation: Any) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_bytes_sequence_annotation(arg): at_least_one = True continue return at_least_one return field_annotation_is_sequence(annotation) and all( is_bytes_or_nonable_bytes_annotation(sub_annotation) for sub_annotation in get_args(annotation) ) def is_uploadfile_sequence_annotation(annotation: Any) -> bool: origin = get_origin(annotation) if origin is Union or origin is UnionType: at_least_one = False for arg in get_args(annotation): if is_uploadfile_sequence_annotation(arg): at_least_one = True continue return at_least_one return field_annotation_is_sequence(annotation) and all( is_uploadfile_or_nonable_uploadfile_annotation(sub_annotation) for sub_annotation in get_args(annotation) ) def is_pydantic_v1_model_instance(obj: Any) -> bool: with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) from pydantic import v1 return isinstance(obj, v1.BaseModel) def is_pydantic_v1_model_class(cls: Any) -> bool: with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) from pydantic import v1 return lenient_issubclass(cls, v1.BaseModel) def annotation_is_pydantic_v1(annotation: Any) -> bool: if is_pydantic_v1_model_class(annotation): return True origin = get_origin(annotation) if origin is Union or origin is UnionType: for arg in get_args(annotation): if is_pydantic_v1_model_class(arg): return True if field_annotation_is_sequence(annotation): for sub_annotation in get_args(annotation): if annotation_is_pydantic_v1(sub_annotation): return True return False
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/_compat/__init__.py
fastapi/_compat/__init__.py
from .shared import PYDANTIC_V2 as PYDANTIC_V2 from .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE from .shared import annotation_is_pydantic_v1 as annotation_is_pydantic_v1 from .shared import field_annotation_is_scalar as field_annotation_is_scalar from .shared import is_pydantic_v1_model_class as is_pydantic_v1_model_class from .shared import is_pydantic_v1_model_instance as is_pydantic_v1_model_instance from .shared import ( is_uploadfile_or_nonable_uploadfile_annotation as is_uploadfile_or_nonable_uploadfile_annotation, ) from .shared import ( is_uploadfile_sequence_annotation as is_uploadfile_sequence_annotation, ) from .shared import lenient_issubclass as lenient_issubclass from .shared import sequence_types as sequence_types from .shared import value_is_sequence as value_is_sequence from .v2 import BaseConfig as BaseConfig from .v2 import ModelField as ModelField from .v2 import PydanticSchemaGenerationError as PydanticSchemaGenerationError from .v2 import RequiredParam as RequiredParam from .v2 import Undefined as Undefined from .v2 import UndefinedType as UndefinedType from .v2 import Url as Url from .v2 import Validator as Validator from .v2 import _regenerate_error_with_loc as _regenerate_error_with_loc from .v2 import copy_field_info as copy_field_info from .v2 import create_body_model as create_body_model from .v2 import evaluate_forwardref as evaluate_forwardref from .v2 import get_cached_model_fields as get_cached_model_fields from .v2 import get_compat_model_name_map as get_compat_model_name_map from .v2 import get_definitions as get_definitions from .v2 import get_missing_field_error as get_missing_field_error from .v2 import get_schema_from_model_field as get_schema_from_model_field from .v2 import is_bytes_field as is_bytes_field from .v2 import is_bytes_sequence_field as is_bytes_sequence_field from .v2 import is_scalar_field as is_scalar_field from .v2 import is_scalar_sequence_field as is_scalar_sequence_field from .v2 import is_sequence_field as is_sequence_field from .v2 import serialize_sequence_value as serialize_sequence_value from .v2 import ( with_info_plain_validator_function as with_info_plain_validator_function, )
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/_compat/v2.py
fastapi/_compat/v2.py
import re import warnings from collections.abc import Sequence from copy import copy, deepcopy from dataclasses import dataclass, is_dataclass from enum import Enum from functools import lru_cache from typing import ( Annotated, Any, Union, cast, ) from fastapi._compat import shared from fastapi.openapi.constants import REF_TEMPLATE from fastapi.types import IncEx, ModelNameMap, UnionType from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, create_model from pydantic import PydanticSchemaGenerationError as PydanticSchemaGenerationError from pydantic import PydanticUndefinedAnnotation as PydanticUndefinedAnnotation from pydantic import ValidationError as ValidationError from pydantic._internal._schema_generation_shared import ( # type: ignore[attr-defined] GetJsonSchemaHandler as GetJsonSchemaHandler, ) from pydantic._internal._typing_extra import eval_type_lenient from pydantic._internal._utils import lenient_issubclass as lenient_issubclass from pydantic.fields import FieldInfo as FieldInfo from pydantic.json_schema import GenerateJsonSchema as GenerateJsonSchema from pydantic.json_schema import JsonSchemaValue as JsonSchemaValue from pydantic_core import CoreSchema as CoreSchema from pydantic_core import PydanticUndefined, PydanticUndefinedType from pydantic_core import Url as Url from typing_extensions import Literal, get_args, get_origin try: from pydantic_core.core_schema import ( with_info_plain_validator_function as with_info_plain_validator_function, ) except ImportError: # pragma: no cover from pydantic_core.core_schema import ( general_plain_validator_function as with_info_plain_validator_function, # noqa: F401 ) RequiredParam = PydanticUndefined Undefined = PydanticUndefined UndefinedType = PydanticUndefinedType evaluate_forwardref = eval_type_lenient Validator = Any # TODO: remove when dropping support for Pydantic < v2.12.3 _Attrs = { "default": ..., "default_factory": None, "alias": None, "alias_priority": None, "validation_alias": None, "serialization_alias": None, "title": None, "field_title_generator": None, "description": None, "examples": None, "exclude": None, "exclude_if": None, "discriminator": None, "deprecated": None, "json_schema_extra": None, "frozen": None, "validate_default": None, "repr": True, "init": None, "init_var": None, "kw_only": None, } # TODO: remove when dropping support for Pydantic < v2.12.3 def asdict(field_info: FieldInfo) -> dict[str, Any]: attributes = {} for attr in _Attrs: value = getattr(field_info, attr, Undefined) if value is not Undefined: attributes[attr] = value return { "annotation": field_info.annotation, "metadata": field_info.metadata, "attributes": attributes, } class BaseConfig: pass class ErrorWrapper(Exception): pass @dataclass class ModelField: field_info: FieldInfo name: str mode: Literal["validation", "serialization"] = "validation" config: Union[ConfigDict, None] = None @property def alias(self) -> str: a = self.field_info.alias return a if a is not None else self.name @property def validation_alias(self) -> Union[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]: sa = self.field_info.serialization_alias return sa or None @property def required(self) -> bool: return self.field_info.is_required() @property def default(self) -> Any: return self.get_default() @property def type_(self) -> Any: return self.field_info.annotation def __post_init__(self) -> None: with warnings.catch_warnings(): # Pydantic >= 2.12.0 warns about field specific metadata that is unused # (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we # end up building the type adapter from a model field annotation so we # need to ignore the warning: if shared.PYDANTIC_VERSION_MINOR_TUPLE >= (2, 12): from pydantic.warnings import UnsupportedFieldAttributeWarning warnings.simplefilter( "ignore", category=UnsupportedFieldAttributeWarning ) # TODO: remove after dropping support for Python 3.8 and # setting the min Pydantic to v2.12.3 that adds asdict() field_dict = asdict(self.field_info) annotated_args = ( field_dict["annotation"], *field_dict["metadata"], # this FieldInfo needs to be created again so that it doesn't include # the old field info metadata and only the rest of the attributes Field(**field_dict["attributes"]), ) self._type_adapter: TypeAdapter[Any] = TypeAdapter( Annotated[annotated_args], config=self.config, ) def get_default(self) -> Any: if self.field_info.is_required(): return Undefined return self.field_info.get_default(call_default_factory=True) def validate( self, value: Any, values: dict[str, Any] = {}, # noqa: B006 *, loc: tuple[Union[int, str], ...] = (), ) -> tuple[Any, Union[list[dict[str, Any]], None]]: try: return ( self._type_adapter.validate_python(value, from_attributes=True), None, ) except ValidationError as exc: return None, _regenerate_error_with_loc( errors=exc.errors(include_url=False), loc_prefix=loc ) def serialize( self, value: Any, *, mode: Literal["json", "python"] = "json", include: Union[IncEx, None] = None, exclude: Union[IncEx, None] = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> Any: # What calls this code passes a value that already called # self._type_adapter.validate_python(value) return self._type_adapter.dump_python( value, mode=mode, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) def __hash__(self) -> int: # Each ModelField is unique for our purposes, to allow making a dict from # ModelField to its JSON Schema. return id(self) def _has_computed_fields(field: ModelField) -> bool: computed_fields = field._type_adapter.core_schema.get("schema", {}).get( "computed_fields", [] ) return len(computed_fields) > 0 def get_schema_from_model_field( *, field: ModelField, model_name_map: ModelNameMap, field_mapping: dict[ tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], separate_input_output_schemas: bool = True, ) -> dict[str, Any]: override_mode: Union[Literal["validation"], None] = ( None if (separate_input_output_schemas or _has_computed_fields(field)) else "validation" ) field_alias = ( (field.validation_alias or field.alias) if field.mode == "validation" else (field.serialization_alias or field.alias) ) # This expects that GenerateJsonSchema was already used to generate the definitions json_schema = field_mapping[(field, override_mode or field.mode)] if "$ref" not in json_schema: # TODO remove when deprecating Pydantic v1 # Ref: https://github.com/pydantic/pydantic/blob/d61792cc42c80b13b23e3ffa74bc37ec7c77f7d1/pydantic/schema.py#L207 json_schema["title"] = field.field_info.title or field_alias.title().replace( "_", " " ) return json_schema def get_definitions( *, fields: Sequence[ModelField], model_name_map: ModelNameMap, separate_input_output_schemas: bool = True, ) -> tuple[ dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], dict[str, dict[str, Any]], ]: schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE) validation_fields = [field for field in fields if field.mode == "validation"] serialization_fields = [field for field in fields if field.mode == "serialization"] flat_validation_models = get_flat_models_from_fields( validation_fields, known_models=set() ) flat_serialization_models = get_flat_models_from_fields( serialization_fields, known_models=set() ) flat_validation_model_fields = [ ModelField( field_info=FieldInfo(annotation=model), name=model.__name__, mode="validation", ) for model in flat_validation_models ] flat_serialization_model_fields = [ ModelField( field_info=FieldInfo(annotation=model), name=model.__name__, mode="serialization", ) for model in flat_serialization_models ] flat_model_fields = flat_validation_model_fields + flat_serialization_model_fields input_types = {f.type_ for f in fields} unique_flat_model_fields = { f for f in flat_model_fields if f.type_ not in input_types } inputs = [ ( field, ( field.mode if (separate_input_output_schemas or _has_computed_fields(field)) else "validation" ), field._type_adapter.core_schema, ) for field in list(fields) + list(unique_flat_model_fields) ] field_mapping, definitions = schema_generator.generate_definitions(inputs=inputs) for item_def in cast(dict[str, dict[str, Any]], definitions).values(): if "description" in item_def: item_description = cast(str, item_def["description"]).split("\f")[0] item_def["description"] = item_description new_mapping, new_definitions = _remap_definitions_and_field_mappings( model_name_map=model_name_map, definitions=definitions, # type: ignore[arg-type] field_mapping=field_mapping, ) return new_mapping, new_definitions def _replace_refs( *, schema: dict[str, Any], old_name_to_new_name_map: dict[str, str], ) -> dict[str, Any]: new_schema = deepcopy(schema) for key, value in new_schema.items(): if key == "$ref": value = schema["$ref"] if isinstance(value, str): ref_name = schema["$ref"].split("/")[-1] if ref_name in old_name_to_new_name_map: new_name = old_name_to_new_name_map[ref_name] new_schema["$ref"] = REF_TEMPLATE.format(model=new_name) continue if isinstance(value, dict): new_schema[key] = _replace_refs( schema=value, old_name_to_new_name_map=old_name_to_new_name_map, ) elif isinstance(value, list): new_value = [] for item in value: if isinstance(item, dict): new_item = _replace_refs( schema=item, old_name_to_new_name_map=old_name_to_new_name_map, ) new_value.append(new_item) else: new_value.append(item) new_schema[key] = new_value return new_schema def _remap_definitions_and_field_mappings( *, model_name_map: ModelNameMap, definitions: dict[str, Any], field_mapping: dict[ tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ], ) -> tuple[ dict[tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue], dict[str, Any], ]: old_name_to_new_name_map = {} for field_key, schema in field_mapping.items(): model = field_key[0].type_ if model not in model_name_map or "$ref" not in schema: continue new_name = model_name_map[model] old_name = schema["$ref"].split("/")[-1] if old_name in {f"{new_name}-Input", f"{new_name}-Output"}: continue old_name_to_new_name_map[old_name] = new_name new_field_mapping: dict[ tuple[ModelField, Literal["validation", "serialization"]], JsonSchemaValue ] = {} for field_key, schema in field_mapping.items(): new_schema = _replace_refs( schema=schema, old_name_to_new_name_map=old_name_to_new_name_map, ) new_field_mapping[field_key] = new_schema new_definitions = {} for key, value in definitions.items(): if key in old_name_to_new_name_map: new_key = old_name_to_new_name_map[key] else: new_key = key new_value = _replace_refs( schema=value, old_name_to_new_name_map=old_name_to_new_name_map, ) new_definitions[new_key] = new_value return new_field_mapping, new_definitions def is_scalar_field(field: ModelField) -> bool: from fastapi import params return shared.field_annotation_is_scalar( field.field_info.annotation ) and not isinstance(field.field_info, params.Body) def is_sequence_field(field: ModelField) -> bool: return shared.field_annotation_is_sequence(field.field_info.annotation) def is_scalar_sequence_field(field: ModelField) -> bool: return shared.field_annotation_is_scalar_sequence(field.field_info.annotation) def is_bytes_field(field: ModelField) -> bool: return shared.is_bytes_or_nonable_bytes_annotation(field.type_) def is_bytes_sequence_field(field: ModelField) -> bool: return shared.is_bytes_sequence_annotation(field.type_) def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo: cls = type(field_info) merged_field_info = cls.from_annotation(annotation) new_field_info = copy(field_info) new_field_info.metadata = merged_field_info.metadata new_field_info.annotation = merged_field_info.annotation return new_field_info def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]: origin_type = get_origin(field.field_info.annotation) or field.field_info.annotation if origin_type is Union or origin_type is UnionType: # Handle optional sequences union_args = get_args(field.field_info.annotation) for union_arg in union_args: if union_arg is type(None): continue origin_type = get_origin(union_arg) or union_arg break assert issubclass(origin_type, shared.sequence_types) # type: ignore[arg-type] return shared.sequence_annotation_to_type[origin_type](value) # type: ignore[no-any-return,index] def get_missing_field_error(loc: tuple[str, ...]) -> dict[str, Any]: error = ValidationError.from_exception_data( "Field required", [{"type": "missing", "loc": loc, "input": {}}] ).errors(include_url=False)[0] error["input"] = None return error # type: ignore[return-value] def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> type[BaseModel]: field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} BodyModel: type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] return BodyModel def get_model_fields(model: type[BaseModel]) -> list[ModelField]: model_fields: list[ModelField] = [] for name, field_info in model.model_fields.items(): type_ = field_info.annotation if lenient_issubclass(type_, (BaseModel, dict)) or is_dataclass(type_): model_config = None else: model_config = model.model_config model_fields.append( ModelField( field_info=field_info, name=name, config=model_config, ) ) return model_fields @lru_cache def get_cached_model_fields(model: type[BaseModel]) -> list[ModelField]: return get_model_fields(model) # type: ignore[return-value] # 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]] TypeModelSet = set[TypeModelOrEnum] def normalize_name(name: str) -> str: return re.sub(r"[^a-zA-Z0-9.\-_]", "_", name) def get_model_name_map(unique_models: TypeModelSet) -> dict[TypeModelOrEnum, str]: name_model_map = {} for model in unique_models: model_name = normalize_name(model.__name__) name_model_map[model_name] = model return {v: k for k, v in name_model_map.items()} def get_compat_model_name_map(fields: list[ModelField]) -> ModelNameMap: all_flat_models = set() v2_model_fields = [field for field in fields if isinstance(field, ModelField)] v2_flat_models = get_flat_models_from_fields(v2_model_fields, known_models=set()) all_flat_models = all_flat_models.union(v2_flat_models) # type: ignore[arg-type] model_name_map = get_model_name_map(all_flat_models) # type: ignore[arg-type] return model_name_map def get_flat_models_from_model( model: type["BaseModel"], known_models: Union[TypeModelSet, None] = None ) -> TypeModelSet: known_models = known_models or set() fields = get_model_fields(model) get_flat_models_from_fields(fields, known_models=known_models) return known_models def get_flat_models_from_annotation( annotation: Any, known_models: TypeModelSet ) -> TypeModelSet: origin = get_origin(annotation) if origin is not None: for arg in get_args(annotation): if lenient_issubclass(arg, (BaseModel, Enum)) and arg not in known_models: known_models.add(arg) if lenient_issubclass(arg, BaseModel): get_flat_models_from_model(arg, known_models=known_models) else: get_flat_models_from_annotation(arg, known_models=known_models) return known_models def get_flat_models_from_field( field: ModelField, known_models: TypeModelSet ) -> TypeModelSet: field_type = field.type_ if lenient_issubclass(field_type, BaseModel): if field_type in known_models: return known_models known_models.add(field_type) get_flat_models_from_model(field_type, known_models=known_models) elif lenient_issubclass(field_type, Enum): known_models.add(field_type) else: get_flat_models_from_annotation(field_type, known_models=known_models) return known_models def get_flat_models_from_fields( fields: Sequence[ModelField], known_models: TypeModelSet ) -> TypeModelSet: for field in fields: get_flat_models_from_field(field, known_models=known_models) return known_models def _regenerate_error_with_loc( *, errors: Sequence[Any], loc_prefix: tuple[Union[str, int], ...] ) -> list[dict[str, Any]]: updated_loc_errors: list[Any] = [ {**err, "loc": loc_prefix + err.get("loc", ())} for err in errors ] return updated_loc_errors
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/openapi/constants.py
fastapi/openapi/constants.py
METHODS_WITH_BODY = {"GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} REF_PREFIX = "#/components/schemas/" REF_TEMPLATE = "#/components/schemas/{model}"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/openapi/models.py
fastapi/openapi/models.py
from collections.abc import Iterable, Mapping from enum import Enum from typing import Annotated, Any, Callable, Optional, Union from fastapi._compat import with_info_plain_validator_function from fastapi.logger import logger from pydantic import ( AnyUrl, BaseModel, Field, GetJsonSchemaHandler, ) from typing_extensions import Literal, TypedDict from typing_extensions import deprecated as typing_deprecated try: import email_validator assert email_validator # make autoflake ignore the unused import from pydantic import EmailStr except ImportError: # pragma: no cover class EmailStr(str): # type: ignore @classmethod def __get_validators__(cls) -> Iterable[Callable[..., Any]]: yield cls.validate @classmethod def validate(cls, v: Any) -> str: logger.warning( "email-validator not installed, email fields will be treated as str.\n" "To install, run: pip install email-validator" ) return str(v) @classmethod def _validate(cls, __input_value: Any, _: Any) -> str: logger.warning( "email-validator not installed, email fields will be treated as str.\n" "To install, run: pip install email-validator" ) return str(__input_value) @classmethod def __get_pydantic_json_schema__( cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler ) -> dict[str, Any]: return {"type": "string", "format": "email"} @classmethod def __get_pydantic_core_schema__( cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] ) -> Mapping[str, Any]: return with_info_plain_validator_function(cls._validate) class BaseModelWithConfig(BaseModel): model_config = {"extra": "allow"} class Contact(BaseModelWithConfig): name: Optional[str] = None url: Optional[AnyUrl] = None email: Optional[EmailStr] = None class License(BaseModelWithConfig): name: str identifier: Optional[str] = None url: Optional[AnyUrl] = 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 version: str class ServerVariable(BaseModelWithConfig): enum: Annotated[Optional[list[str]], Field(min_length=1)] = None default: str description: Optional[str] = None class Server(BaseModelWithConfig): url: Union[AnyUrl, str] description: Optional[str] = None variables: Optional[dict[str, ServerVariable]] = None class Reference(BaseModel): ref: str = Field(alias="$ref") class Discriminator(BaseModel): propertyName: str mapping: Optional[dict[str, str]] = None class XML(BaseModelWithConfig): name: Optional[str] = None namespace: Optional[str] = None prefix: Optional[str] = None attribute: Optional[bool] = None wrapped: Optional[bool] = None class ExternalDocumentation(BaseModelWithConfig): description: Optional[str] = None url: AnyUrl # Ref JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation#name-type SchemaType = Literal[ "array", "boolean", "integer", "null", "number", "object", "string" ] 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") # 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 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 # TODO: uncomment and remove below when deprecating Pydantic v1 # It generates a list of schemas for tuples, before prefixItems was available # items: Optional["SchemaOrBool"] = None items: Optional[Union["SchemaOrBool", list["SchemaOrBool"]]] = None contains: Optional["SchemaOrBool"] = None properties: Optional[dict[str, "SchemaOrBool"]] = None patternProperties: Optional[dict[str, "SchemaOrBool"]] = 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 # 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 # 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 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 # 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 example: Annotated[ Optional[Any], typing_deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = None # 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] class Example(TypedDict, total=False): summary: Optional[str] description: Optional[str] value: Optional[Any] externalValue: Optional[AnyUrl] __pydantic_config__ = {"extra": "allow"} # type: ignore[misc] class ParameterInType(Enum): query = "query" header = "header" path = "path" cookie = "cookie" 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 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 class ParameterBase(BaseModelWithConfig): description: Optional[str] = None required: Optional[bool] = None deprecated: Optional[bool] = 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 # Serialization rules for more complex scenarios content: Optional[dict[str, MediaType]] = None class Parameter(ParameterBase): name: str in_: ParameterInType = Field(alias="in") class Header(ParameterBase): pass class RequestBody(BaseModelWithConfig): description: Optional[str] = None content: dict[str, MediaType] required: Optional[bool] = 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 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 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 # 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 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 class SecuritySchemeType(Enum): apiKey = "apiKey" http = "http" oauth2 = "oauth2" openIdConnect = "openIdConnect" class SecurityBase(BaseModelWithConfig): type_: SecuritySchemeType = Field(alias="type") description: Optional[str] = None class APIKeyIn(Enum): query = "query" header = "header" cookie = "cookie" class APIKey(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.apiKey, alias="type") in_: APIKeyIn = Field(alias="in") name: str class HTTPBase(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.http, alias="type") scheme: str class HTTPBearer(HTTPBase): scheme: Literal["bearer"] = "bearer" bearerFormat: Optional[str] = None class OAuthFlow(BaseModelWithConfig): refreshUrl: Optional[str] = None scopes: dict[str, str] = {} class OAuthFlowImplicit(OAuthFlow): authorizationUrl: str class OAuthFlowPassword(OAuthFlow): tokenUrl: str class OAuthFlowClientCredentials(OAuthFlow): tokenUrl: str class OAuthFlowAuthorizationCode(OAuthFlow): authorizationUrl: str tokenUrl: str class OAuthFlows(BaseModelWithConfig): implicit: Optional[OAuthFlowImplicit] = None password: Optional[OAuthFlowPassword] = None clientCredentials: Optional[OAuthFlowClientCredentials] = None authorizationCode: Optional[OAuthFlowAuthorizationCode] = None class OAuth2(SecurityBase): type_: SecuritySchemeType = Field(default=SecuritySchemeType.oauth2, alias="type") flows: OAuthFlows class OpenIdConnect(SecurityBase): type_: SecuritySchemeType = Field( default=SecuritySchemeType.openIdConnect, alias="type" ) openIdConnectUrl: str SecurityScheme = Union[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 # Using Any for Specification Extensions callbacks: Optional[dict[str, Union[dict[str, PathItem], Reference, Any]]] = None pathItems: Optional[dict[str, Union[PathItem, Reference]]] = None class Tag(BaseModelWithConfig): name: str description: Optional[str] = None externalDocs: Optional[ExternalDocumentation] = None class OpenAPI(BaseModelWithConfig): openapi: str info: Info jsonSchemaDialect: Optional[str] = None servers: Optional[list[Server]] = 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 Schema.model_rebuild() Operation.model_rebuild() Encoding.model_rebuild()
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/openapi/utils.py
fastapi/openapi/utils.py
import http.client import inspect import warnings from collections.abc import Sequence from typing import Any, Optional, Union, cast from fastapi import routing from fastapi._compat import ( ModelField, Undefined, get_compat_model_name_map, get_definitions, get_schema_from_model_field, lenient_issubclass, ) from fastapi.datastructures import DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( _get_flat_fields_from_params, get_flat_dependant, get_flat_params, get_validation_alias, ) from fastapi.encoders import jsonable_encoder from fastapi.exceptions import FastAPIDeprecationWarning from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX from fastapi.openapi.models import OpenAPI from fastapi.params import Body, ParamTypes from fastapi.responses import Response from fastapi.types import ModelNameMap from fastapi.utils import ( deep_dict_update, generate_operation_id_for_path, is_body_allowed_for_status_code, ) from pydantic import BaseModel from starlette.responses import JSONResponse from starlette.routing import BaseRoute from typing_extensions import Literal validation_error_definition = { "title": "ValidationError", "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, "required": ["loc", "msg", "type"], } validation_error_response_definition = { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": REF_PREFIX + "ValidationError"}, } }, } status_code_ranges: dict[str, str] = { "1XX": "Information", "2XX": "Success", "3XX": "Redirection", "4XX": "Client Error", "5XX": "Server Error", "DEFAULT": "Default Response", } def get_openapi_security_definitions( flat_dependant: Dependant, ) -> tuple[dict[str, Any], list[dict[str, Any]]]: security_definitions = {} # Use a dict to merge scopes for same security scheme operation_security_dict: dict[str, list[str]] = {} for security_dependency in flat_dependant._security_dependencies: security_definition = jsonable_encoder( security_dependency._security_scheme.model, by_alias=True, exclude_none=True, ) security_name = security_dependency._security_scheme.scheme_name security_definitions[security_name] = security_definition # Merge scopes for the same security scheme if security_name not in operation_security_dict: operation_security_dict[security_name] = [] for scope in security_dependency.oauth_scopes or []: if scope not in operation_security_dict[security_name]: operation_security_dict[security_name].append(scope) operation_security = [ {name: scopes} for name, scopes in operation_security_dict.items() ] return security_definitions, operation_security def _get_openapi_operation_parameters( *, dependant: Dependant, model_name_map: ModelNameMap, field_mapping: dict[ tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any] ], separate_input_output_schemas: bool = True, ) -> list[dict[str, Any]]: parameters = [] flat_dependant = get_flat_dependant(dependant, skip_repeats=True) path_params = _get_flat_fields_from_params(flat_dependant.path_params) query_params = _get_flat_fields_from_params(flat_dependant.query_params) header_params = _get_flat_fields_from_params(flat_dependant.header_params) cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) parameter_groups = [ (ParamTypes.path, path_params), (ParamTypes.query, query_params), (ParamTypes.header, header_params), (ParamTypes.cookie, cookie_params), ] default_convert_underscores = True if len(flat_dependant.header_params) == 1: first_field = flat_dependant.header_params[0] if lenient_issubclass(first_field.type_, BaseModel): default_convert_underscores = getattr( first_field.field_info, "convert_underscores", True ) for param_type, param_group in parameter_groups: for param in param_group: field_info = param.field_info # field_info = cast(Param, field_info) if not getattr(field_info, "include_in_schema", True): continue param_schema = get_schema_from_model_field( field=param, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) name = get_validation_alias(param) convert_underscores = getattr( param.field_info, "convert_underscores", default_convert_underscores, ) if ( param_type == ParamTypes.header and name == param.name and convert_underscores ): name = param.name.replace("_", "-") parameter = { "name": name, "in": param_type.value, "required": param.required, "schema": param_schema, } if field_info.description: parameter["description"] = field_info.description openapi_examples = getattr(field_info, "openapi_examples", None) example = getattr(field_info, "example", None) if openapi_examples: parameter["examples"] = jsonable_encoder(openapi_examples) elif example != Undefined: parameter["example"] = jsonable_encoder(example) if getattr(field_info, "deprecated", None): parameter["deprecated"] = True parameters.append(parameter) return parameters def get_openapi_operation_request_body( *, body_field: Optional[ModelField], 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]]: if not body_field: return None assert isinstance(body_field, ModelField) body_schema = get_schema_from_model_field( field=body_field, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) field_info = cast(Body, body_field.field_info) request_media_type = field_info.media_type required = body_field.required request_body_oai: dict[str, Any] = {} if required: request_body_oai["required"] = required request_media_content: dict[str, Any] = {"schema": body_schema} if field_info.openapi_examples: request_media_content["examples"] = jsonable_encoder( field_info.openapi_examples ) elif field_info.example != Undefined: request_media_content["example"] = jsonable_encoder(field_info.example) request_body_oai["content"] = {request_media_type: request_media_content} return request_body_oai def generate_operation_id( *, route: routing.APIRoute, method: str ) -> str: # pragma: nocover warnings.warn( message="fastapi.openapi.utils.generate_operation_id() was deprecated, " "it is not used internally, and will be removed soon", category=FastAPIDeprecationWarning, stacklevel=2, ) if route.operation_id: return route.operation_id path: str = route.path_format return generate_operation_id_for_path(name=route.name, path=path, method=method) def generate_operation_summary(*, route: routing.APIRoute, method: str) -> str: if route.summary: return route.summary return route.name.replace("_", " ").title() def get_openapi_operation_metadata( *, route: routing.APIRoute, method: str, operation_ids: set[str] ) -> dict[str, Any]: operation: dict[str, Any] = {} if route.tags: operation["tags"] = route.tags operation["summary"] = generate_operation_summary(route=route, method=method) if route.description: operation["description"] = route.description operation_id = route.operation_id or route.unique_id if operation_id in operation_ids: message = ( f"Duplicate Operation ID {operation_id} for function " + f"{route.endpoint.__name__}" ) file_name = getattr(route.endpoint, "__globals__", {}).get("__file__") if file_name: message += f" at {file_name}" warnings.warn(message, stacklevel=1) operation_ids.add(operation_id) operation["operationId"] = operation_id if route.deprecated: operation["deprecated"] = route.deprecated return operation def get_openapi_path( *, route: routing.APIRoute, operation_ids: set[str], model_name_map: ModelNameMap, field_mapping: dict[ tuple[ModelField, Literal["validation", "serialization"]], dict[str, Any] ], separate_input_output_schemas: bool = True, ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: path = {} security_schemes: dict[str, Any] = {} definitions: dict[str, Any] = {} assert route.methods is not None, "Methods must be a list" if isinstance(route.response_class, DefaultPlaceholder): current_response_class: type[Response] = route.response_class.value 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 if route.include_in_schema: for method in route.methods: operation = get_openapi_operation_metadata( route=route, method=method, operation_ids=operation_ids ) parameters: list[dict[str, Any]] = [] flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True) security_definitions, operation_security = get_openapi_security_definitions( flat_dependant=flat_dependant ) if operation_security: operation.setdefault("security", []).extend(operation_security) if security_definitions: security_schemes.update(security_definitions) operation_parameters = _get_openapi_operation_parameters( dependant=route.dependant, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) parameters.extend(operation_parameters) if parameters: all_parameters = { (param["in"], param["name"]): param for param in parameters } required_parameters = { (param["in"], param["name"]): param for param in parameters if param.get("required") } # Make sure required definitions of the same parameter take precedence # over non-required definitions all_parameters.update(required_parameters) operation["parameters"] = list(all_parameters.values()) if method in METHODS_WITH_BODY: request_body_oai = get_openapi_operation_request_body( body_field=route.body_field, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) if request_body_oai: operation["requestBody"] = request_body_oai if route.callbacks: callbacks = {} for callback in route.callbacks: if isinstance(callback, routing.APIRoute): ( cb_path, cb_security_schemes, cb_definitions, ) = get_openapi_path( route=callback, operation_ids=operation_ids, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) callbacks[callback.name] = {callback.path: cb_path} operation["callbacks"] = callbacks if route.status_code is not None: status_code = str(route.status_code) else: # It would probably make more sense for all response classes to have an # explicit default status_code, and to extract it from them, instead of # doing this inspection tricks, that would probably be in the future # TODO: probably make status_code a default class attribute for all # responses in Starlette response_signature = inspect.signature(current_response_class.__init__) status_code_param = response_signature.parameters.get("status_code") if status_code_param is not None: if isinstance(status_code_param.default, int): status_code = str(status_code_param.default) operation.setdefault("responses", {}).setdefault(status_code, {})[ "description" ] = route.response_description if route_response_media_type and is_body_allowed_for_status_code( route.status_code ): response_schema = {"type": "string"} if lenient_issubclass(current_response_class, JSONResponse): if route.response_field: response_schema = get_schema_from_model_field( field=route.response_field, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) else: response_schema = {} operation.setdefault("responses", {}).setdefault( status_code, {} ).setdefault("content", {}).setdefault(route_response_media_type, {})[ "schema" ] = response_schema if route.responses: operation_responses = operation.setdefault("responses", {}) for ( additional_status_code, additional_response, ) in route.responses.items(): process_response = additional_response.copy() process_response.pop("model", None) status_code_key = str(additional_status_code).upper() if status_code_key == "DEFAULT": status_code_key = "default" openapi_response = operation_responses.setdefault( status_code_key, {} ) assert isinstance(process_response, dict), ( "An additional response must be a dict" ) field = route.response_fields.get(additional_status_code) additional_field_schema: Optional[dict[str, Any]] = None if field: additional_field_schema = get_schema_from_model_field( field=field, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) media_type = route_response_media_type or "application/json" additional_schema = ( process_response.setdefault("content", {}) .setdefault(media_type, {}) .setdefault("schema", {}) ) deep_dict_update(additional_schema, additional_field_schema) status_text: Optional[str] = status_code_ranges.get( str(additional_status_code).upper() ) or http.client.responses.get(int(additional_status_code)) description = ( process_response.get("description") or openapi_response.get("description") or status_text or "Additional Response" ) deep_dict_update(openapi_response, process_response) openapi_response["description"] = description http422 = "422" all_route_params = get_flat_params(route.dependant) if (all_route_params or route.body_field) and not any( status in operation["responses"] for status in [http422, "4XX", "default"] ): operation["responses"][http422] = { "description": "Validation Error", "content": { "application/json": { "schema": {"$ref": REF_PREFIX + "HTTPValidationError"} } }, } if "ValidationError" not in definitions: definitions.update( { "ValidationError": validation_error_definition, "HTTPValidationError": validation_error_response_definition, } ) if route.openapi_extra: deep_dict_update(operation, route.openapi_extra) path[method.lower()] = operation return path, security_schemes, definitions def get_fields_from_routes( routes: Sequence[BaseRoute], ) -> list[ModelField]: body_fields_from_routes: list[ModelField] = [] responses_from_routes: list[ModelField] = [] request_fields_from_routes: list[ModelField] = [] callback_flat_models: list[ModelField] = [] for route in routes: if getattr(route, "include_in_schema", None) and isinstance( route, routing.APIRoute ): if route.body_field: assert isinstance(route.body_field, ModelField), ( "A request body must be a Pydantic Field" ) body_fields_from_routes.append(route.body_field) if route.response_field: responses_from_routes.append(route.response_field) if route.response_fields: responses_from_routes.extend(route.response_fields.values()) if route.callbacks: callback_flat_models.extend(get_fields_from_routes(route.callbacks)) params = get_flat_params(route.dependant) request_fields_from_routes.extend(params) flat_models = callback_flat_models + list( body_fields_from_routes + responses_from_routes + request_fields_from_routes ) return flat_models def get_openapi( *, title: str, version: str, openapi_version: str = "3.1.0", summary: Optional[str] = None, description: Optional[str] = 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, separate_input_output_schemas: bool = True, external_docs: Optional[dict[str, Any]] = None, ) -> dict[str, Any]: info: dict[str, Any] = {"title": title, "version": version} if summary: info["summary"] = summary if description: info["description"] = description if terms_of_service: info["termsOfService"] = terms_of_service if contact: info["contact"] = contact if license_info: info["license"] = license_info output: dict[str, Any] = {"openapi": openapi_version, "info": info} if servers: output["servers"] = servers components: dict[str, dict[str, Any]] = {} paths: dict[str, dict[str, Any]] = {} webhook_paths: dict[str, dict[str, Any]] = {} operation_ids: set[str] = set() all_fields = get_fields_from_routes(list(routes or []) + list(webhooks or [])) model_name_map = get_compat_model_name_map(all_fields) field_mapping, definitions = get_definitions( fields=all_fields, model_name_map=model_name_map, separate_input_output_schemas=separate_input_output_schemas, ) for route in routes or []: if isinstance(route, routing.APIRoute): result = get_openapi_path( route=route, operation_ids=operation_ids, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) if result: path, security_schemes, path_definitions = result if path: paths.setdefault(route.path_format, {}).update(path) if security_schemes: components.setdefault("securitySchemes", {}).update( security_schemes ) if path_definitions: definitions.update(path_definitions) for webhook in webhooks or []: if isinstance(webhook, routing.APIRoute): result = get_openapi_path( route=webhook, operation_ids=operation_ids, model_name_map=model_name_map, field_mapping=field_mapping, separate_input_output_schemas=separate_input_output_schemas, ) if result: path, security_schemes, path_definitions = result if path: webhook_paths.setdefault(webhook.path_format, {}).update(path) if security_schemes: components.setdefault("securitySchemes", {}).update( security_schemes ) if path_definitions: definitions.update(path_definitions) if definitions: components["schemas"] = {k: definitions[k] for k in sorted(definitions)} if components: output["components"] = components output["paths"] = paths if webhook_paths: output["webhooks"] = webhook_paths if tags: output["tags"] = tags if external_docs: output["externalDocs"] = external_docs return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/openapi/__init__.py
fastapi/openapi/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/fastapi/openapi/docs.py
fastapi/openapi/docs.py
import json from typing import Annotated, Any, Optional from annotated_doc import Doc from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse swagger_ui_default_parameters: Annotated[ dict[str, Any], Doc( """ Default configurations for Swagger UI. You can use it as a template to add any other configurations needed. """ ), ] = { "dom_id": "#swagger-ui", "layout": "BaseLayout", "deepLinking": True, "showExtensions": True, "showCommonExtensions": True, } def get_swagger_ui_html( *, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that Swagger UI should load and use. This is normally done automatically by FastAPI using the default URL `/openapi.json`. """ ), ], title: Annotated[ str, Doc( """ The HTML `<title>` content, normally shown in the browser tab. """ ), ], swagger_js_url: Annotated[ str, Doc( """ The URL to use to load the Swagger UI JavaScript. It is normally set to a CDN URL. """ ), ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url: Annotated[ str, Doc( """ The URL to use to load the Swagger UI CSS. It is normally set to a CDN URL. """ ), ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", swagger_favicon_url: Annotated[ str, Doc( """ The URL of the favicon to use. It is normally shown in the browser tab. """ ), ] = "https://fastapi.tiangolo.com/img/favicon.png", oauth2_redirect_url: Annotated[ Optional[str], Doc( """ The OAuth2 redirect URL, it is normally automatically handled by FastAPI. """ ), ] = None, init_oauth: Annotated[ Optional[dict[str, Any]], Doc( """ A dictionary with Swagger UI OAuth2 initialization configurations. """ ), ] = None, swagger_ui_parameters: Annotated[ Optional[dict[str, Any]], Doc( """ Configuration parameters for Swagger UI. It defaults to [swagger_ui_default_parameters][fastapi.openapi.docs.swagger_ui_default_parameters]. """ ), ] = None, ) -> HTMLResponse: """ Generate and return the HTML that loads Swagger UI for the interactive API docs (normally served at `/docs`). You would only call this function yourself if you needed to override some parts, for example the URLs to use to load Swagger UI's JavaScript and CSS. Read more about it in the [FastAPI docs for Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/) and the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). """ current_swagger_ui_parameters = swagger_ui_default_parameters.copy() if swagger_ui_parameters: current_swagger_ui_parameters.update(swagger_ui_parameters) html = f""" <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="{swagger_css_url}"> <link rel="shortcut icon" href="{swagger_favicon_url}"> <title>{title}</title> </head> <body> <div id="swagger-ui"> </div> <script src="{swagger_js_url}"></script> <!-- `SwaggerUIBundle` is now available on the page --> <script> const ui = SwaggerUIBundle({{ url: '{openapi_url}', """ for key, value in current_swagger_ui_parameters.items(): html += f"{json.dumps(key)}: {json.dumps(jsonable_encoder(value))},\n" if oauth2_redirect_url: html += f"oauth2RedirectUrl: window.location.origin + '{oauth2_redirect_url}'," html += """ presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], })""" if init_oauth: html += f""" ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))}) """ html += """ </script> </body> </html> """ return HTMLResponse(html) def get_redoc_html( *, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that ReDoc should load and use. This is normally done automatically by FastAPI using the default URL `/openapi.json`. """ ), ], title: Annotated[ str, Doc( """ The HTML `<title>` content, normally shown in the browser tab. """ ), ], redoc_js_url: Annotated[ str, Doc( """ The URL to use to load the ReDoc JavaScript. It is normally set to a CDN URL. """ ), ] = "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js", redoc_favicon_url: Annotated[ str, Doc( """ The URL of the favicon to use. It is normally shown in the browser tab. """ ), ] = "https://fastapi.tiangolo.com/img/favicon.png", with_google_fonts: Annotated[ bool, Doc( """ Load and use Google Fonts. """ ), ] = True, ) -> HTMLResponse: """ Generate and return the HTML response that loads ReDoc for the alternative API docs (normally served at `/redoc`). You would only call this function yourself if you needed to override some parts, for example the URLs to use to load ReDoc's JavaScript and CSS. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). """ html = f""" <!DOCTYPE html> <html> <head> <title>{title}</title> <!-- needed for adaptive design --> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> """ if with_google_fonts: html += """ <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet"> """ html += f""" <link rel="shortcut icon" href="{redoc_favicon_url}"> <!-- ReDoc doesn't change outer page styles --> <style> body {{ margin: 0; padding: 0; }} </style> </head> <body> <noscript> ReDoc requires Javascript to function. Please enable it to browse the documentation. </noscript> <redoc spec-url="{openapi_url}"></redoc> <script src="{redoc_js_url}"> </script> </body> </html> """ return HTMLResponse(html) def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: """ Generate the HTML response with the OAuth2 redirection for Swagger UI. You normally don't need to use or change this. """ # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html html = """ <!doctype html> <html lang="en-US"> <head> <title>Swagger UI: OAuth2 Redirect</title> </head> <body> <script> 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr; if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1).replace('?', '&'); } else { qp = location.search.substring(1); } arr = qp.split("&"); arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';}); qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value); } ) : {}; isValid = qp.state === sentState; if (( oauth2.auth.schema.get("flow") === "accessCode" || oauth2.auth.schema.get("flow") === "authorizationCode" || oauth2.auth.schema.get("flow") === "authorization_code" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server." }); } if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg; if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); } oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server." }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); } if (document.readyState !== 'loading') { run(); } else { document.addEventListener('DOMContentLoaded', function () { run(); }); } </script> </body> </html> """ return HTMLResponse(content=html)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/body_fields/tutorial001_py39.py
docs_src/body_fields/tutorial001_py39.py
from typing import Union from fastapi import Body, FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str description: Union[str, None] = Field( default=None, title="The description of the item", max_length=300 ) price: float = Field(gt=0, description="The price must be greater than zero") tax: Union[float, None] = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item = Body(embed=True)): results = {"item_id": item_id, "item": item} return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/body_fields/tutorial001_an_py39.py
docs_src/body_fields/tutorial001_an_py39.py
from typing import Annotated, Union from fastapi import Body, FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str description: Union[str, None] = Field( default=None, title="The description of the item", max_length=300 ) price: float = Field(gt=0, description="The price must be greater than zero") tax: Union[float, None] = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]): results = {"item_id": item_id, "item": item} return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/body_fields/__init__.py
docs_src/body_fields/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/body_fields/tutorial001_an_py310.py
docs_src/body_fields/tutorial001_an_py310.py
from typing import Annotated from fastapi import Body, FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str description: str | None = Field( default=None, title="The description of the item", max_length=300 ) price: float = Field(gt=0, description="The price must be greater than zero") tax: float | None = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]): results = {"item_id": item_id, "item": item} return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/body_fields/tutorial001_py310.py
docs_src/body_fields/tutorial001_py310.py
from fastapi import Body, FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str description: str | None = Field( default=None, title="The description of the item", max_length=300 ) price: float = Field(gt=0, description="The price must be greater than zero") tax: float | None = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item = Body(embed=True)): results = {"item_id": item_id, "item": item} return results
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_change_status_code/tutorial001_py39.py
docs_src/response_change_status_code/tutorial001_py39.py
from fastapi import FastAPI, Response, status app = FastAPI() tasks = {"foo": "Listen to the Bar Fighters"} @app.put("/get-or-create-task/{task_id}", status_code=200) def get_or_create_task(task_id: str, response: Response): if task_id not in tasks: tasks[task_id] = "This didn't exist before" response.status_code = status.HTTP_201_CREATED return tasks[task_id]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_change_status_code/__init__.py
docs_src/response_change_status_code/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/__init__.py
docs_src/bigger_applications/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/dependencies.py
docs_src/bigger_applications/app_an_py39/dependencies.py
from typing import Annotated from fastapi import Header, HTTPException async def get_token_header(x_token: Annotated[str, Header()]): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def get_query_token(token: str): if token != "jessica": raise HTTPException(status_code=400, detail="No Jessica token provided")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/main.py
docs_src/bigger_applications/app_an_py39/main.py
from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) app.include_router(items.router) app.include_router( admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(get_token_header)], responses={418: {"description": "I'm a teapot"}}, ) @app.get("/") async def root(): return {"message": "Hello Bigger Applications!"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/__init__.py
docs_src/bigger_applications/app_an_py39/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/internal/admin.py
docs_src/bigger_applications/app_an_py39/internal/admin.py
from fastapi import APIRouter router = APIRouter() @router.post("/") async def update_admin(): return {"message": "Admin getting schwifty"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/internal/__init__.py
docs_src/bigger_applications/app_an_py39/internal/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/routers/users.py
docs_src/bigger_applications/app_an_py39/routers/users.py
from fastapi import APIRouter router = APIRouter() @router.get("/users/", tags=["users"]) async def read_users(): return [{"username": "Rick"}, {"username": "Morty"}] @router.get("/users/me", tags=["users"]) async def read_user_me(): return {"username": "fakecurrentuser"} @router.get("/users/{username}", tags=["users"]) async def read_user(username: str): return {"username": username}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/routers/items.py
docs_src/bigger_applications/app_an_py39/routers/items.py
from fastapi import APIRouter, Depends, HTTPException from ..dependencies import get_token_header router = APIRouter( prefix="/items", tags=["items"], dependencies=[Depends(get_token_header)], responses={404: {"description": "Not found"}}, ) fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}} @router.get("/") async def read_items(): return fake_items_db @router.get("/{item_id}") async def read_item(item_id: str): if item_id not in fake_items_db: raise HTTPException(status_code=404, detail="Item not found") return {"name": fake_items_db[item_id]["name"], "item_id": item_id} @router.put( "/{item_id}", tags=["custom"], responses={403: {"description": "Operation forbidden"}}, ) async def update_item(item_id: str): if item_id != "plumbus": raise HTTPException( status_code=403, detail="You can only update the item: plumbus" ) return {"item_id": item_id, "name": "The great Plumbus"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_an_py39/routers/__init__.py
docs_src/bigger_applications/app_an_py39/routers/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/dependencies.py
docs_src/bigger_applications/app_py39/dependencies.py
from fastapi import Header, HTTPException async def get_token_header(x_token: str = Header()): if x_token != "fake-super-secret-token": raise HTTPException(status_code=400, detail="X-Token header invalid") async def get_query_token(token: str): if token != "jessica": raise HTTPException(status_code=400, detail="No Jessica token provided")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/main.py
docs_src/bigger_applications/app_py39/main.py
from fastapi import Depends, FastAPI from .dependencies import get_query_token, get_token_header from .internal import admin from .routers import items, users app = FastAPI(dependencies=[Depends(get_query_token)]) app.include_router(users.router) app.include_router(items.router) app.include_router( admin.router, prefix="/admin", tags=["admin"], dependencies=[Depends(get_token_header)], responses={418: {"description": "I'm a teapot"}}, ) @app.get("/") async def root(): return {"message": "Hello Bigger Applications!"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/__init__.py
docs_src/bigger_applications/app_py39/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/internal/admin.py
docs_src/bigger_applications/app_py39/internal/admin.py
from fastapi import APIRouter router = APIRouter() @router.post("/") async def update_admin(): return {"message": "Admin getting schwifty"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/internal/__init__.py
docs_src/bigger_applications/app_py39/internal/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/routers/users.py
docs_src/bigger_applications/app_py39/routers/users.py
from fastapi import APIRouter router = APIRouter() @router.get("/users/", tags=["users"]) async def read_users(): return [{"username": "Rick"}, {"username": "Morty"}] @router.get("/users/me", tags=["users"]) async def read_user_me(): return {"username": "fakecurrentuser"} @router.get("/users/{username}", tags=["users"]) async def read_user(username: str): return {"username": username}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/routers/items.py
docs_src/bigger_applications/app_py39/routers/items.py
from fastapi import APIRouter, Depends, HTTPException from ..dependencies import get_token_header router = APIRouter( prefix="/items", tags=["items"], dependencies=[Depends(get_token_header)], responses={404: {"description": "Not found"}}, ) fake_items_db = {"plumbus": {"name": "Plumbus"}, "gun": {"name": "Portal Gun"}} @router.get("/") async def read_items(): return fake_items_db @router.get("/{item_id}") async def read_item(item_id: str): if item_id not in fake_items_db: raise HTTPException(status_code=404, detail="Item not found") return {"name": fake_items_db[item_id]["name"], "item_id": item_id} @router.put( "/{item_id}", tags=["custom"], responses={403: {"description": "Operation forbidden"}}, ) async def update_item(item_id: str): if item_id != "plumbus": raise HTTPException( status_code=403, detail="You can only update the item: plumbus" ) return {"item_id": item_id, "name": "The great Plumbus"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/bigger_applications/app_py39/routers/__init__.py
docs_src/bigger_applications/app_py39/routers/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial006c_py39.py
docs_src/custom_response/tutorial006c_py39.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/pydantic", response_class=RedirectResponse, status_code=302) async def redirect_pydantic(): return "https://docs.pydantic.dev/"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial009b_py39.py
docs_src/custom_response/tutorial009b_py39.py
from fastapi import FastAPI from fastapi.responses import FileResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/", response_class=FileResponse) async def main(): return some_file_path
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial001b_py39.py
docs_src/custom_response/tutorial001b_py39.py
from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI() @app.get("/items/", response_class=ORJSONResponse) async def read_items(): return ORJSONResponse([{"item_id": "Foo"}])
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial004_py39.py
docs_src/custom_response/tutorial004_py39.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() def generate_html_response(): html_content = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """ return HTMLResponse(content=html_content, status_code=200) @app.get("/items/", response_class=HTMLResponse) async def read_items(): return generate_html_response()
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial001_py39.py
docs_src/custom_response/tutorial001_py39.py
from fastapi import FastAPI from fastapi.responses import UJSONResponse app = FastAPI() @app.get("/items/", response_class=UJSONResponse) async def read_items(): return [{"item_id": "Foo"}]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial005_py39.py
docs_src/custom_response/tutorial005_py39.py
from fastapi import FastAPI from fastapi.responses import PlainTextResponse app = FastAPI() @app.get("/", response_class=PlainTextResponse) async def main(): return "Hello World"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial009c_py39.py
docs_src/custom_response/tutorial009c_py39.py
from typing import Any import orjson from fastapi import FastAPI, Response app = FastAPI() class CustomORJSONResponse(Response): media_type = "application/json" def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed" return orjson.dumps(content, option=orjson.OPT_INDENT_2) @app.get("/", response_class=CustomORJSONResponse) async def main(): return {"message": "Hello World"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial007_py39.py
docs_src/custom_response/tutorial007_py39.py
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() async def fake_video_streamer(): for i in range(10): yield b"some fake video bytes" @app.get("/") async def main(): return StreamingResponse(fake_video_streamer())
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial010_py39.py
docs_src/custom_response/tutorial010_py39.py
from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI(default_response_class=ORJSONResponse) @app.get("/items/") async def read_items(): return [{"item_id": "Foo"}]
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial006_py39.py
docs_src/custom_response/tutorial006_py39.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/typer") async def redirect_typer(): return RedirectResponse("https://typer.tiangolo.com")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial008_py39.py
docs_src/custom_response/tutorial008_py39.py
from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") def main(): def iterfile(): # (1) with open(some_file_path, mode="rb") as file_like: # (2) yield from file_like # (3) return StreamingResponse(iterfile(), media_type="video/mp4")
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial006b_py39.py
docs_src/custom_response/tutorial006b_py39.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/fastapi", response_class=RedirectResponse) async def redirect_fastapi(): return "https://fastapi.tiangolo.com"
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial009_py39.py
docs_src/custom_response/tutorial009_py39.py
from fastapi import FastAPI from fastapi.responses import FileResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") async def main(): return FileResponse(some_file_path)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/__init__.py
docs_src/custom_response/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial002_py39.py
docs_src/custom_response/tutorial002_py39.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/items/", response_class=HTMLResponse) async def read_items(): return """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/custom_response/tutorial003_py39.py
docs_src/custom_response/tutorial003_py39.py
from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/items/") async def read_items(): html_content = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """ return HTMLResponse(content=html_content, status_code=200)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extra_data_types/tutorial001_py39.py
docs_src/extra_data_types/tutorial001_py39.py
from datetime import datetime, time, timedelta from typing import Union from uuid import UUID from fastapi import Body, FastAPI app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, start_datetime: datetime = Body(), end_datetime: datetime = Body(), process_after: timedelta = Body(), repeat_at: Union[time, None] = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process return { "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, "process_after": process_after, "repeat_at": repeat_at, "start_process": start_process, "duration": duration, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extra_data_types/tutorial001_an_py39.py
docs_src/extra_data_types/tutorial001_an_py39.py
from datetime import datetime, time, timedelta from typing import Annotated, Union from uuid import UUID from fastapi import Body, FastAPI app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, start_datetime: Annotated[datetime, Body()], end_datetime: Annotated[datetime, Body()], process_after: Annotated[timedelta, Body()], repeat_at: Annotated[Union[time, None], Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process return { "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, "process_after": process_after, "repeat_at": repeat_at, "start_process": start_process, "duration": duration, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extra_data_types/__init__.py
docs_src/extra_data_types/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extra_data_types/tutorial001_an_py310.py
docs_src/extra_data_types/tutorial001_an_py310.py
from datetime import datetime, time, timedelta from typing import Annotated from uuid import UUID from fastapi import Body, FastAPI app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, start_datetime: Annotated[datetime, Body()], end_datetime: Annotated[datetime, Body()], process_after: Annotated[timedelta, Body()], repeat_at: Annotated[time | None, Body()] = None, ): start_process = start_datetime + process_after duration = end_datetime - start_process return { "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, "process_after": process_after, "repeat_at": repeat_at, "start_process": start_process, "duration": duration, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/extra_data_types/tutorial001_py310.py
docs_src/extra_data_types/tutorial001_py310.py
from datetime import datetime, time, timedelta from uuid import UUID from fastapi import Body, FastAPI app = FastAPI() @app.put("/items/{item_id}") async def read_items( item_id: UUID, start_datetime: datetime = Body(), end_datetime: datetime = Body(), process_after: timedelta = Body(), repeat_at: time | None = Body(default=None), ): start_process = start_datetime + process_after duration = end_datetime - start_process return { "item_id": item_id, "start_datetime": start_datetime, "end_datetime": end_datetime, "process_after": process_after, "repeat_at": repeat_at, "start_process": start_process, "duration": duration, }
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/async_tests/__init__.py
docs_src/async_tests/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/async_tests/app_a_py39/test_main.py
docs_src/async_tests/app_a_py39/test_main.py
import pytest from httpx import ASGITransport, AsyncClient from .main import app @pytest.mark.anyio async def test_root(): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: response = await ac.get("/") assert response.status_code == 200 assert response.json() == {"message": "Tomato"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/async_tests/app_a_py39/main.py
docs_src/async_tests/app_a_py39/main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Tomato"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/async_tests/app_a_py39/__init__.py
docs_src/async_tests/app_a_py39/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_headers/tutorial001_py39.py
docs_src/response_headers/tutorial001_py39.py
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.get("/headers/") def get_headers(): content = {"message": "Hello World"} headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"} return JSONResponse(content=content, headers=headers)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_headers/__init__.py
docs_src/response_headers/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/response_headers/tutorial002_py39.py
docs_src/response_headers/tutorial002_py39.py
from fastapi import FastAPI, Response app = FastAPI() @app.get("/headers-and-object/") def get_headers(response: Response): response.headers["X-Cat-Dog"] = "alone in the world" return {"message": "Hello World"}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/authentication_error_status_code/tutorial001_an_py39.py
docs_src/authentication_error_status_code/tutorial001_an_py39.py
from typing import Annotated from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer app = FastAPI() class HTTPBearer403(HTTPBearer): def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated" ) CredentialsDep = Annotated[HTTPAuthorizationCredentials, Depends(HTTPBearer403())] @app.get("/me") def read_me(credentials: CredentialsDep): return {"message": "You are authenticated", "token": credentials.credentials}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/authentication_error_status_code/__init__.py
docs_src/authentication_error_status_code/__init__.py
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial001_03_an_py39.py
docs_src/request_files/tutorial001_03_an_py39.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File(description="A file read as bytes")]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file( file: Annotated[UploadFile, File(description="A file read as UploadFile")], ): return {"filename": file.filename}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial001_02_an_py310.py
docs_src/request_files/tutorial001_02_an_py310.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes | None, File()] = None): if not file: return {"message": "No file sent"} else: return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile | None = None): if not file: return {"message": "No upload file sent"} else: return {"filename": file.filename}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial002_an_py39.py
docs_src/request_files/tutorial002_an_py39.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files(files: Annotated[list[bytes], File()]): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files(files: list[UploadFile]): return {"filenames": [file.filename for file in files]} @app.get("/") async def main(): content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial003_an_py39.py
docs_src/request_files/tutorial003_an_py39.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile from fastapi.responses import HTMLResponse app = FastAPI() @app.post("/files/") async def create_files( files: Annotated[list[bytes], File(description="Multiple files as bytes")], ): return {"file_sizes": [len(file) for file in files]} @app.post("/uploadfiles/") async def create_upload_files( files: Annotated[ list[UploadFile], File(description="Multiple files as UploadFile") ], ): return {"filenames": [file.filename for file in files]} @app.get("/") async def main(): content = """ <body> <form action="/files/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> <form action="/uploadfiles/" enctype="multipart/form-data" method="post"> <input name="files" type="file" multiple> <input type="submit"> </form> </body> """ return HTMLResponse(content=content)
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial001_py39.py
docs_src/request_files/tutorial001_py39.py
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: bytes = File()): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial001_an_py39.py
docs_src/request_files/tutorial001_an_py39.py
from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes, File()]): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile): return {"filename": file.filename}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false
fastapi/fastapi
https://github.com/fastapi/fastapi/blob/f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a/docs_src/request_files/tutorial001_03_py39.py
docs_src/request_files/tutorial001_03_py39.py
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: bytes = File(description="A file read as bytes")): return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file( file: UploadFile = File(description="A file read as UploadFile"), ): return {"filename": file.filename}
python
MIT
f2687dc1bb01f4cb62eee90e656b61c38c2aaf6a
2026-01-04T14:38:15.465144Z
false